/**
 * @file 工单列表
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/12/03 11:05:40
 * zmn.mos.order.add.common.js
 */

var dependsList = [
    "index",
    "layer",
    "form",
    "table",
    "laydate",
    "util",
    "zmn_validate",
    "zmnUtils",
    "$http",
    "select2",
    "validator",
    "Vue",
    "dayjs",
    "upload",
    "previewer",
    "zmnOmsSelect",
    "clipboard"
];
//记录产品总数
var allnumber = 0;

layui.define(dependsList, function(exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var validate = layui.zmn_validate;
    var util = layui.util;
    var zmnUtils = layui.zmnUtils;
    var $http = layui.$http;
    var Vue = layui.Vue;
    var dayjs = layui.dayjs;
    var table = layui.table;
    let upload = layui.upload;
    var previewer = layui.previewer;
    let zmnOmsSelect = layui.zmnOmsSelect;
    var clipboard = layui.clipboard;

  var debounceTimer;
  var orderPostTable;
  var maxProductCount = 1;
  var reqCountyName;
  var discountData = [];
  var countyData = [];
  //是否平台直派
  var isGrid;
  // 是否查询预派工程师
  var isSelectMaster = true;
  var isWhiteWorkCity = false;
  var isAutoDistributeTimeWithin = false;
  var isAvailableWeeks = [];
  // 默认真实号码
  var isRealCallTelephone = true;


    // 优惠批次信息 三层嵌套 手机号、页面产品index、批次
    // {"tel":{index:{batchId1:discountInfo,batchId2:discountInfo}}}
    // 对象
    let discountTelephoneMap = new Map();
    let bestDiscountTelephoneMap = new Map();
    let currProductIndex = 0;

    let isAdvanceQuoteGlobal = false;

    window.EventBus = new Vue({
        el: "#omsApp",
        data: {
            list: [{
                brandId: "",
                productId: "",
                showProductId: "",
                productShowType: "",
                number: "",
                remark: "",
                faultIdList: "",
                categId: "",
                servCategId: 1,
            }, ],
            removeList: [],
        },
        mounted() {
            // addProductEvenFunc(0)
            var that = this;
            setTimeout(function() {
                addFormEvent("product0", "showProduct0", "servCategory0", 0);
                initProduct("", "", that.list.length - 1);
                var str = "servCategoryA0";
                form.render();
            }, 1000);
        },
        methods: {
            //添加按钮
            addFunc() {
                //(this);
                if (this.list.length > 19) {
                    layer.alert("最多添加20个产品", { offset: "250px" });
                    return;
                }
                this.list.push({
                    brandId: "",
                    productId: "",
                    showProductId: "",
                    productShowType: "",
                    number: "",
                    remark: "",
                    faultIdList: "",
                    categId: "",
                    servCategId: 1,
                });
                const that = this;
                // form.render(null,'servCategoryA'+(that.list.length - 1));
                this.$nextTick(function() {
                    addProductEvenFunc(that.list.length - 1);
                    initProduct("", "", that.list.length - 1);
                    // //('servCategoryA'+(that.list.length - 1))
                });

                //清空快递信息
                $("#moreModal .layui-input").val("");
                if (orderPostTable) {
                    orderPostTable.reload({
                        data: [],
                    });
                }

                // 清理预付款凭证
                $("#channelPrepayAmount").val("");
                $("#channelPrepayCertificateImgSrcValue").val("");
                $("#channelPrepayType").addClass("layui-hide");
                $("#channelPrepayCertificateImgSrc").attr("style", "");
                $("#upload-icon").attr("style", "");
                $("#upload-p").attr("style", "");
                layui.form.val('zmn-order-add-form', { channelPrepayRadio: '1' });
            },
            //删除按钮
            removeFunc(index) {
                //(index);
                this.removeList.push(index);
                //(this.removeList);
                // this.list.splice(index, 1);
                if (this.list.length == this.removeList.length + 1) {
                    initCompanyInfo();
                    initGridCompany();
                }
            },
            //选择预约时间事件
            chooseTimeFunc(index) {
                var layer = parent.layui.layer;

        if (!getters.getCityId()) {
          layer.alert("请选择城市", { offset: "250px" });
          return;
        }
        //下单地址录入校验
        if (!getters.getLatitude() || !getters.getLongitude()){
            layer.alert("请先填写下单地址", { offset: "250px" });
            return;
        }

        //服务产品校验
        if (!getters.getProductId()){
          layer.alert("请先选择服务产品", { offset: "250px" });
          return;
        }

        var productId = getLayuiSelectValue("#product" + index);
        var showProductId = getLayuiSelectValue("#showProduct" + index)

        var costIndex = index;

        layer.open({
          title: "选择预约时间",
          type: 2,
          shift: 7,
          area: ["980px", "650px"],
          fix: true,
          offset: ["6px"],
          zIndex: 99999999999,
          content: OMS_BASE_URL + "/order/dutytime",
          success: function (layero) {
            parent.layer.setTop(layero);
            parent.window.dutyTimeOptions = {
              dutyTime: newGetters.getDutyTime(costIndex),
              plat: getters.getPlat(),
              platWork: getters.getPlatWork(),
              channelId: getters.getChannelId(),
              cityId: getters.getCityId(),
              productId: productId,
              showProductId: showProductId,
              workId: getters.getWorkId(),
              type: getters.getOrderType(),
              latitude: getters.getLatitude(),
              longitude: getters.getLongitude(),
              isGrid: isGrid,
              productNum: newGetters.getCount(costIndex),
              servCategId: newGetters.getServCategId(costIndex),
              bizType: getters.getBizType(),
              isAvailableWeek: isAvailableWeeks[costIndex],
              confirm: function (time,changeData) {
                //(time);
                selectDutyTimeInfo(time, time, costIndex);
                // 更新服务商信息
                initCompanyInfo(time);
                // 计算派单工程师
                // calculateDistributeMaster(costIndex);
              },
            };
          },
        });
      },
      //添加查看价格表事件
      readPriceFunc(index) {
        var cityId = getters.getCityId();
        var productId = newGetters.getProductId(index);
        var channelId = getters.getChannelId();
        var bizType = getters.getBizType();
        var type = getters.getType();
        var plat = getters.getPlat();
        var brandId = newGetters.getBrandId(index) || 1051;
        var productShowType = newGetters.getProductShowType(index);

                if (!channelId) {
                    layer.msg("请先选择渠道");
                    return;
                }

                if (!cityId) {
                    layer.msg("请先选择城市");
                    return;
                }

                if (!productId) {
                    layer.msg("请先选择产品");
                    return;
                }

                if (!brandId) {
                    layer.msg("请先选择品牌");
                    return;
                }

                var priceTableURL = zmnUtils.serializeURL(PRODUCT_PRICE_TABLE_URL, {
                    cityId: cityId,
                    productId: productId,
                    channelId: channelId,
                    bizType: bizType || 1, // 默认保外
                    brandId: brandId,
                    tariffType: productShowType,
                    type: type,
                    plat: plat
                });

                layer.open({
                    type: 2,
                    title: "价格表",
                    content: priceTableURL,
                    shade: [0.8, "#393D49"],
                    area: ["98%", "96vh"],
                });
            },
            //添加查看优惠信息事件
            readDiscountFunc(index) {
                $('#show-discount-div' + index).html('');
                    // 渠道id
                if ($('#show-discount-div' + index)[0].className == 'hidden') {
                    $('#show-discount-div' + index)[0].className = 'show'
                } else {
                    $('#show-discount-div' + index)[0].className = 'hidden'
                }
                if (!getters.getChannelId()) {
                    return;
                }

                // 城市id
                if (!getters.getCityId()) {
                    return;
                }

                // 产品id
                if (!newGetters.getProductId(index)) {
                    return;
                }

                var price = $("#amount" + index).data("price");
                if (!price) {
                    price = null;
                }

                // 批次集合
                let batchListJson = "";
                if (discountTelephoneMap.get(getters.getTelephone()) && discountTelephoneMap.get(getters.getTelephone()).get(index)) {
                    let batchList = Array.from(discountTelephoneMap.get(getters.getTelephone()).get(index).values()).map((batch) => JSON.stringify(batch));
                    batchListJson = "[" + batchList.join(",") + "]";
                }
                $http
                    .$get(GET_SHOW_DISCOUNT_URL, {
                        plat: getters.getPlat(),
                        platWork: getters.getPlatWork(),
                        channelId: getters.getChannelId(),
                        cityId: getters.getCityId(),
                        productId: newGetters.getProductId(index),
                        showType: newGetters.getProductShowType(index),
                        bizType: getters.getBizType(),
                        type: getters.getType(),
                        servItemType: $("#servItemType" + index).val(),
                        price: price,
                        telephone: getters.getTelephone(),
                        brandId: newGetters.getBrandId(index),
                        productNum: newGetters.getCount(index),
                        batchListJson: batchListJson,
                        receiveEntranceId: getters.getReceiveEntranceId(),
                    })
                    .then(
                        function(data) {
                            // 标记当前操作的产品位置
                            currProductIndex = index;
                            let url = SYS_BASE_URL_ENUM.dms + data;
                            var dom = '<iframe scrolling="auto" allowtransparency="true" frameborder="0" src="' + url + '" style="height: 382px;width: 100%;"></iframe>'
                            $('#show-discount-div' + index).html(dom);
                            // 打开弹窗
                            // layer.open({
                            //         type: 2,
                            //         title: "查看优惠信息",
                            //         area: ["1150px", "425px"],
                            //         fix: true,
                            //         zIndex: 99999999999,
                            //         content: SYS_BASE_URL_ENUM.dms + data,
                            //         shade: [0.8, "#393D49"],
                            //         success: function (layero) {
                            //         },
                            //         cancel: function () {
                            //           currProductIndex = 0;
                            //
                            //           // 获取当前产品价格信息
                            //           reloadDiscountInfo(price, index, true);
                            //         }
                            //       });
                        },
                        function(msg) {
                            layer.msg(msg);
                        }
                    );

                // let discountIndex = index;
                // layer.open({
                //   type: 2,
                //   title: "查看优惠信息",
                //   area: ["1150px", "425px"],
                //   fix: true,
                //   zIndex: 99999999999,
                //   content: OMS_BASE_URL + SHOW_DISCOUNT_URL,
                //   shade: [0.8, "#393D49"],
                //   success: function (layero) {
                //     window.showDiscountOptions = {
                //       promotionDiscountList: discountData[discountIndex].promotionDiscountList,
                //       userDiscountList: discountData[discountIndex].userDiscountList,
                //       thirdDiscountList: discountData[discountIndex].thirdDiscountList,
                //       incrementDiscountList: discountData[discountIndex].incrementDiscountList,
                //       userBindDiscountList: discountData[discountIndex].userBindDiscountList
                //     };
                //   },
                // });
            },
            //检测是否被删除，是否需要隐藏
            checkRemove(index) {
                return !this.removeList.includes(index);
            },
        },
    });

    var objOfURL = {
        workDetail: "/work/detail.action",
        workModifyDetail: "/work/modify/detail.action",
        savePurpose: "/order/purpose/save.action",
        checkCityIsWhiteCity: "/work/stock/checkCityIsWhiteCity.action",
    };

    var options = {
        saveURL: null,
        isNew: false,
        isEntrust: false,
        isDistributeMaster: false,
        modifyDetail: false,
        enableExternalShop: false,
        success: () => {},
    };

    // 检查价格表工单产品数量是否为1
    var isQuotationCanSave = (list) => {
        var flag = true;

        $.each(list, function(index, value) {
            if (
                isQuotation(value.servItemType) &&
                !(value.number == 1)
            ) {
                flag = false;
                layer.msg("计价器工单产品数量必须为1");
                return flag;
            }
        });
        return flag;
    };

    function verifyBeforeSubmit(list) {
        // 计价器产品数量必须为1
        if (!isQuotationCanSave(list)) {
            return false;
        }
        return true;
    }

    // 城市
    var cityData = {};

    // 获取省份、城市、区域
    var CITY_URL = "/area/permit/city/list.action";
    var COUNTY_URL = "/area/list.action";
    var AREA_DETAIL_URL = "/area/detail/list.action";
    var CHECK_CHANNELID_CITYID_URL = "/area/check/channel_city.action";
    var GET_CHANNEL_PREPAY_TYPE_URL = "/common/getChannelPrepayType.action";
    // 渠道订单配置
    var GET_CHANNEL_CONF_URL = "/conf/channel/getChannelInfo.action";
    // 外部店铺数据
    var GET_EXTERNAL_SHOP_URL = "/shop/list/marketing.action";

    // 获取公司信息
    var COMPANY_URL = "/company/getCompanyName.action";
    // 获取行政服务商名称
    var GRID_COMPANY_URL = "/company/getGridCompanyName.action";

    // 获取产品列表
    var PRODUCT_URL = "/serv/product/list.action";

    // 获取常见故障
    var PRODUCT_SUBSIDIARY_URL = "/serv/product/subsidiary/list.action";

    // 获取小区地址信息
    var COMMUNITY_ADDRESS_URL = "/area/queryCommunity.action";
    // 百度地图地址联想
    var BAIDU_MAP_SUGGESTED = "//api.map.baidu.com/place/v2/suggestion";

    // 校验地址是否在服务范围
    var STREET_VALIDATION_URL = "/area/checkServicePoint.action";

    // 根据经纬度获取区域信息
    var AREA_INFO_URL = "/area/getAreaInfo.action";

    // 产品价格表页面地址
    var PRODUCT_PRICE_TABLE_URL = "/order/getProductPriceTable";

    // 提前报价价格表页面地址
    var ADVANCE_PRODUCT_PRICE_TABLE_URL = "/order/advance/getProductPriceTable";

    // 提前报价故障现象价格表页面地址
    var ADVANCE_PRODUCT_PHEN_PRICE_TABLE_URL = "/order/advance/getPhenProductPriceTable";

  // 获取工单类型以及默认服务项信息
  var GET_SERVITEM_TYPE_INFO_WORK_URL = "/order/getServItemTypeAndInfo.action";
  // 根据渠道、城市、产品类型获取服务分类
  var GET_SERV_CATEG_BY_CITY_CHANNEL_SHOWTYPE_URL =
      "/serv/category/listByCityIdAndChannelIdAndShowType.action";
  // 获取默认预约时间
  var GET_DEFAULT_DUTYTIME = "/schedule/back/defaultTime.action";
  // 检查是否平台直派
  var IS_GRID = "/common/check/grid.action";
  // 获取自动派单时间
  var GET_AUTO_DISTRIBUTE_TIME = "/common/getAutoDistributeTime.action";
  // 检查是否可以下拉选择
  var CHECK_PRODECT = "/serv/check/repeat/product.action";
  // 检查是否有优惠
  var CHECK_DISCOUNT_URL = "/common/check/discount.action";
  // 优惠信息页面
  var SHOW_DISCOUNT_URL = "/common/show/discount.action";
  // 校验服务商
  var CHECK_COMPANY_URL = "/order/check/company.action";
  // 订单数量页面
  var GET_ORDER_SAME_NUMBER_URL = "/order/same/number.action";
  // 订单查询页
  var ZMN_ORDER_LIST_URL = "/work/list.action";
  // 获取真是手机号路径
  var GET_REAL_PHONE_URL = "/order/normal/getRealPhone";
  var GET_DECRYPT_PHONE_URL = "/order/normal/getDecryptPhone";
  // 获取预派工程师信息
  var GET_PRE_DISTRIBUTE_MASTER_URL = "/work/modify/pre/distribute/master";
  // 根据产品信息获取对应产品组信息
  var GET_CATEG_PRODUCT_GROUP = "/serv/product/group/getCategProductGroup.action";
    // 获取优惠页面信息
    var GET_SHOW_DISCOUNT_URL = "/work/addOrder/getDiscountURL";
    // 获取下单优惠信息
    var GET_ADD_ORDER_DISCOUNT_URL = "/work/addOrder/getDiscountDetail";
    // 检查重复单信息， 重复返回true
    var GET_DUPLICATE_ORDER_ID_URL = "/order/check/duplicateOrder";
    // 校验疫情
    let CHECK_EPIDEMIC_CONTROL_URL = "/order/check/epidemicControl";

    // 校验提前付试点
    let CHECK_ADVANCE_QUOTE_URL = "/order/advance/checkAdvance";
    // 获取提前付相关信息
    let GET_QUOTE_INFO_URL = "/order/advance/getQuoteInfo";

    // 获取故障现象列表
    let LIST_PHEN_URL = "/order/advance/listFaultPhen";
    // 获取提前付服务项报价二级分类(故障现象)
    let LIST_PRODUCT_CATEG_WITH_PHEN_ID_URL = "/order/advance/listProductCateg";
    // 获取提前付故障现象获取产品
    let LIST_PRODUCT_WITH_PHEN_URL = "/order/advance/listProduct";

    // 获取服务项列表
    let LIST_SERVICE_ITEM_URL = "/order/advance/listServiceItem";
    // 获取提前付服务项报价二级分类
    let LIST_PRODUCT_CATEG_WITH_ITEM_ID_URL = "/order/advance/listProductCategWithItemId";
    // 获取提前付服务项获取产品
    let LIST_PRODUCT_WITH_ITEM_URL = "/order/advance/listProductWithItem";

    // 转单失败发送短信
    var GET_ORDER_TRANSFER_FAIL_URL = "/sendMessage/orderTransferFail.action";
    // 话务确认报价失败
    var GET_ORDER_CONFIRM_QUOTED_FAIL_URL = "/sendMessage/orderConfirmQuotedFail.action";


    // 工单类型枚举
    var ORDER_TYPE_ENUM = {
        NEW: "1",
        REWORK: "2",
    };

    // 产品显示类型
    var PRODUCT_SHOW_TYPE_ENUM = {
        BACK: "1",
        FRONT: "2",
    };

  // 服务项类型(是否是计价器工单)
  var SERVICE_ITEM_TYPE_ENUM = {
    'SERVICE_ITEM_TYPE_ORDER': '1',
    'SERVICE_ITEM_TYPE_FAULT' : '2',
    'SERVICE_ITEM_TYPE_ADVANCE_PAY' : '3',
    'SERVICE_ITEM_TYPE_QUOTATION_THREE' : '4',
    'SERVICE_ITEM_TYPE_FINAL_PRICE' : '5',
  };

    // 产品列表缓存
    var productCache = {};
    var showProductCache = {};
    var servCategoryCache = {};
    var showCheckCityMsg = false;

  function isQuotation(servItemType) {
    return SERVICE_ITEM_TYPE_ENUM.SERVICE_ITEM_TYPE_FAULT == servItemType
        || SERVICE_ITEM_TYPE_ENUM.SERVICE_ITEM_TYPE_ADVANCE_PAY == servItemType
        || SERVICE_ITEM_TYPE_ENUM.SERVICE_ITEM_TYPE_QUOTATION_THREE == servItemType
        || SERVICE_ITEM_TYPE_ENUM.SERVICE_ITEM_TYPE_FINAL_PRICE == servItemType
        ;
  }

     /**
     * 重复单判断
     */
      function checkDuplicateOrder(index){
          let type = getters.getOrderType();
          if (type != ORDER_TYPE_ENUM.NEW) {
              return;
          }
         if (!isRealCallTelephone) {
             return;
         }
          let productId = newGetters.getProductId(index);
          let productShowType = newGetters.getProductShowType(index);
          let telephone = getters.getTelephone();
          let telephone2 = getters.getTelephone2();
          let telephone3 = getters.getTelephone3();
          if (!productId || !telephone){
            return;
          }

          $http.get(GET_DUPLICATE_ORDER_ID_URL, {
              plat: getters.getPlat(),
              bizType:getters.getBizType(),
              productId:productId,
              productShowType:productShowType,
              telephone:telephone,
              telephone2:telephone2,
              telephone3:telephone3,
          }).then(function (isDuplicate) {
              if (isDuplicate) {
                  $('#order-duplicate-tips'+index).html('此用户有疑似相同的订单正在服务');
              } else {
                  $('#order-duplicate-tips'+index).html('');
              }
          });
      }

    /**
     * 重复单判断
     */
    function checkAllDuplicateOrder(callback){
        let list = window.EventBus.list;
        if (!isRealCallTelephone) {
            return;
        }

        let productIds = [];
        let productShowTypes = [];
        list.forEach(function(item, index) {
            let productId = newGetters.getProductId(index);
            let productShowType = newGetters.getProductShowType(index);
            productIds.push(productId || 0);
            productShowTypes.push(productShowType || 0);
        });

        let telephone = getters.getTelephone();
        let telephone2 = getters.getTelephone2();
        let telephone3 = getters.getTelephone3();

        $http.get(GET_DUPLICATE_ORDER_ID_URL, {
            plat: getters.getPlat(),
            bizType:getters.getBizType(),
            productIdList: productIds.join(','),
            productShowTypeList:productShowTypes.join(','),
            telephone:telephone,
            telephone2:telephone2,
            telephone3:telephone3,
        }).then(function (resultList) {
            let duplicateProductList = [];
            resultList.forEach((isDuplicate, index) => {
                if (isDuplicate) {
                    $('#order-duplicate-tips'+index).html('此用户有疑似相同的订单正在服务');
                    duplicateProductList.push(newGetters.getProductName(index));
                } else {
                    $('#order-duplicate-tips'+index).html('');
                }
            });
            console.log(duplicateProductList);
            if (callback) {
                callback(duplicateProductList);
            }
        });
    }

    /**
     * 远程获取产品数据
     * @param plat 平台
     * @param servCategId 服务项目 id
     * @param cb 回调函数
     */
    function fetchProductData(
        plat,
        servCategId,
        showType,
        cityId,
        channelId,
        bizType,
        index
    ) {
        index;
        return $http.get(PRODUCT_URL, {
            plat: plat,
            servCategId: servCategId,
            showType: newGetters.getProductShowType(index),
            cityId: cityId,
            channelId: channelId,
            bizType: bizType,
            requestId: $('#requestId').val() || ''
        });
    }

    /**
     *校验渠道 选择外部店铺
     * @param cityId 城市 id
     */
    function checkSelectExternalShop(channelId) {

        if (!options.enableExternalShop) {
            return;
        }

        if (!channelId) {
            $('#externalShopInfoSelelct').attr('lay-verify', '');
            $('#externalShopLabel').removeClass('layui-form-required');
            return;
        }

        $http.get(GET_CHANNEL_CONF_URL, {channelId: channelId}).then(
            function (data) {
                if (data.selectMarketingShop == 2) {
                    $('input[name="externalShopInfoSelelct"]').attr('lay-verify', 'required')
                    $('#externalShopLabel').addClass('layui-form-required');
                } else {
                    $('input[name="externalShopInfoSelelct"]').attr('lay-verify', '');
                    $('#externalShopLabel').removeClass('layui-form-required');
                }
            },
            function () {
                $('input[name="externalShopInfoSelelct"]').attr('lay-verify', '');
                $('#externalShopLabel').removeClass('layui-form-required');
            }
        );
    }

    /**
     * 根据产品id
     * @param {string | number} productId 产品id
     * @param {function} cb 回调函数
     */
    function fetchProductSubsidiary(productId) {
        return $http.$get(PRODUCT_SUBSIDIARY_URL, { productId: productId });
    }

    /**
     * 根据父级 id 远程获取下级区域数据
     * @param {string} url 地址
     * @param {object} params 参数
     */
    function fetchAreaDataByParentId(url, params) {
        return $http.get(url, params).then(
            function(data) {
                return data;
            },
            function() {
                layer.msg("获取数据失败");
                return $.Deferred().resolve([]);
            }
        );
    }

    /**
     * 根据省份 id 远程获取城市数据
     * @param provinceId 城市 id
     */
    function fetchCityData(provinceId) {
        return fetchAreaDataByParentId(CITY_URL, {
            provinceId: provinceId,
            channelId: getters.getChannelId(),
            showType: getters.getProductShowType(),
        });
    }

    /**
     * 根据城市 id 远程获取区域数据
     * @param cityId 城市 id
     */
    function fetchAreaData(cityId) {
        return fetchAreaDataByParentId(COUNTY_URL, { parentId: cityId });
    }

    /**
     * 根据城市 id 远程获取区域数据
     * @param cityId 城市 id
     */
    function fetchAreaDetailData(pId) {
        return fetchAreaDataByParentId(AREA_DETAIL_URL, { parentId: pId });
    }

    /**
     * 根据经纬度 远程获取区域数据
     * @param cityId 城市 id
     */
    function fetchAreaInfo(lon, lat) {
        return fetchAreaDataByParentId(AREA_INFO_URL, {
            longitude: lon,
            latitude: lat,
        });
    }

    /**
     * 获取区县信息查询
     */
    function getCountyInfo(countyName) {
        if (!countyName) {
            return null;
        }

        if (countyData.length == 0) {
            $('#county-list').find('span').each(function() {
                var county = {
                    countyId: $(this).data('id'),
                    countyName: $(this).text(),
                };
                countyData.push(county);
            });
        }

        for (var i = 0; i < countyData.length; i++) {
            if (countyName == countyData[i].countyName) {
                return countyData[i];
            }
        }
        return null;
    }

    /**
     * 区县信息查询
     */
    function setCountyInfo(countyName, lng, lat, callback) {
        var cityId = $('#cityId option:selected').val();
        // 本地数据获取countyinfo
        countyName = countyName || '';
        let countyInfo = getCountyInfo(countyName);
        if (countyInfo) {
            updateAreaInfo(countyInfo.countyId);
            if (callback) {
                callback(countyInfo.countyId);
            }
            return;
        }

        // 调用远程接口获取countyinfo
        fetchAreaInfo(lng, lat).then(function(data) {
            if (cityId != data.cityId) {
                switchCity(data.cityId);
            }

            updateAreaInfo(data.countyId);
            if (callback) {
                callback(data.countyId);
            }
        }, function(msg) {
            layer.msg(msg);
        });
    }

    /**
     * 获取百度联想出的地址
     * @param params 查询参数
     * @param cb 回调函数
     */
    function fetchSuggestedStreet(params, cb) {
        fetchBaiduSuggestedStreet(params, cb);
    }

    /**
     * 获取百度联想出的地址
     * @param params 查询参数
     * @param cb 回调函数
     */
    function fetchBaiduSuggestedStreet(params, cb) {
        $.ajax({
            url: BAIDU_MAP_SUGGESTED,
            type: "GET",
            dataType: "jsonp",
            data: {
                query: params.queryStr,
                region: params.cityName,
                city_limit: true,
                output: "json",
                ak: params.ak,
            },
            success: function(response) {
                if (response.status === 0) {
                    // 过滤搜索结果
                    var data = response.result.filter((item) => {
                        if (item.name == item.province || item.name == item.city || item.name == item.district || item.name.endsWith('-道路') || item.name.endsWith('镇') || item.name.endsWith('乡')) {
                            return false;
                        }
                        return (item.city.indexOf(params.cityName.slice(0, 1)) !== -1) || (!item.city && item.district.indexOf(params.cityName.slice(0, 1)) !== -1);
                    });
                    cb(data);
                }
            },
        });
    }

    //检查下拉是否可以选择
    function checkProdect(params, cb1, cb2) {
        $.ajax({
            type: "post",
            url: CHECK_PRODECT,
            data: JSON.stringify(params),
            contentType: "application/json;charset=UTF-8",
            success: function(res) {
                res;
                if (res.statusBool == true) {
                    cb1();
                } else {
                    layer.alert(res.message);
                    cb2();
                }
            },
            error: function() {},
        });
    }

    /**
     * 获取公司信息
     */
    function fetchCompanyName(
        plat,
        channelId,
        cityId,
        type,
        dutyTime,
        workId,
        bizType,
        servCategId,
        productShowType,
        productId,
        longitude,
        latitude,
        streetSource
    ) {
        servCategId = servCategId || 0;
        productShowType = productShowType || 0;
        productId = productId || 0;

        var reqData = {
            callId: getters.getCallId(),
            clueId: getters.getClueId(),
            plat: plat,
            userName: getters.getUserName(),
            gender: getters.getGender(),
            telephone: getters.getTelephone(),
            telephone2: getters.getTelephone2(),
            telephone3: getters.getTelephone3(),
            type: type,
            workId: workId,
            bizType: bizType,
            channelId: channelId,
            channelName: getters.getChannelName(),
            provinceId: getters.getProvinceId(),
            provinceName: getters.getProvinceName(),
            cityId: cityId,
            cityName: getters.getCityName(),
            countyId: getters.getCountyId(),
            countyName: getters.getInputCountyName(),
            streetSource: streetSource,
            streetId: getters.getStreetId(),
            street: getters.getStreet(),
            address: getters.getAddress(),
            longitude: longitude,
            latitude: latitude,
            dutyTime: dutyTime,
            servCategId: servCategId,
            productShowType: productShowType,
            productId: productId,
            test: getters.getTest(),
            remark: getters.getRemark(),
            receiveEntranceId: getters.getReceiveEntranceId(),
            requestId: getters.getRequestId(),
        };



        return $http.$post(COMPANY_URL, reqData);
    }

    /**
     * 保存新普通订单
     * @param {object} params 订单信息
     * @param {function} cb 回调函数
     */
    function saveOrderInfo(params, btn) {
        // 移除禁用标示
        $("select,input").attr("disabled", false);

        return $http.lockSave(options.saveURL, params, btn);
    }

    function beforeSaveOrder(params, data) {
        if (!data) {
            return;
        }
        saveOrderInfo(params, data.elem).then(
            function(data) {
                layer.msg(data.message, { icon: 1, time: 1000 }, function() {
                    zmnUtils.isFunction(options.success) ?
                        options.success(data) :
                        options.modifyDetail ?
                        goWorkModifyDetail(
                            data.orderWork.orderId,
                            data.orderWork.workId
                        ) :
                        goWorkDetail(data.orderWork.orderId, data.orderWork.workId);
                });
            },
            function(msg) {
                if (msg != "no login") {
                    layer.msg(msg);
                }
            }
        );
    }

    /**
     * 保存心愿单
     * @param {object} params 订单信息
     * @param {btn} 按钮
     */
    function savePurpose(params, btn) {
        return $http.lockSave(objOfURL.savePurpose, params, btn);
    }

    function getLayuiSelectValue(selector) {
        return $(selector + " option:selected").val();
    }

    function getLayuiSelectText(selector) {
        return $(selector + " option:selected").text();
    }

    function getLayuiRadioText(selector) {
        return $(selector + ":checked").prop("title");
    }
    /**
     * 全局获取器
     * @type {{getCityId: (function(): jQuery)}}
     */
    var newGetters = {
        getIndex:function (index){
            return index || 0;
        },
        getList: function(arr1, arr2) {
            return arr1.concat(arr2).filter(function(v, i, arr) {
                return arr.indexOf(v) === arr.lastIndexOf(v);
            });
        },
        getServCategId: function(index) {
            return getLayuiSelectValue("#servCategoryId" + newGetters.getIndex(index));
        },
        getDutyTime: function(index) {
            return $("#duty-time-input" + newGetters.getIndex(index)).val();
        },
        getBrandId: function(index) {
            if (getters.getReceiveEntranceId() == '1002') {
                return getLayuiSelectValue("#brand" + newGetters.getIndex(index));
            }
            return getLayuiSelectValue("#brand" + newGetters.getIndex(index)) || 1051;
        },
        getBrandIdWithoutDefaultVal: function(index) {
            return getLayuiSelectValue("#brand" + newGetters.getIndex(index));
        },
        getCount: function(index) {
            var count = $("#count" + newGetters.getIndex(index)).val();
            return Number.parseInt(count) || 0;
        },
        getProductShowType: function(index) {
            return $('input[name="productShowType' + newGetters.getIndex(index) + '"]:checked').val() || 2;
        },
        getProductId: function(index) {
            index = newGetters.getIndex(index);
            if (newGetters.getProductShowType(index) == "1") {
                return getLayuiSelectValue("#product" + index);
            } else {
                return getLayuiSelectValue("#showProduct" + index);
            }
        },
        getProductName: function(index) {
            index = newGetters.getIndex(index);
            if (newGetters.getProductShowType(index) == "1") {
                return getLayuiSelectText("#product" + index);
            } else {
                return getLayuiSelectText("#showProduct" + index);
            }
        },
        getProductCateg: function() {
            if (checkEleShow("#productCategDiv")) {
                return $('input[name="productCategId"]:checked').val();
            } else {
                return null;
            }
        },
        getPhenId: function() {
            if (checkEleShow("#faultPhenDiv")) {
            return $('input[name="phenId"]:checked').val();
            } else {
                return null;
            }
        },
        getPhenName: function() {
            if (checkEleShow("#faultPhenDiv")) {
                return getLayuiRadioText('input[name="phenId"]');
            } else {
                return null;
            }
        },
        getItemId: function() {
            if (checkEleShow("#serviceItemDiv")) {
                return getLayuiSelectValue("#serviceItem");
            } else {
                return null;
            }
        },
        getQuoteProductId: function() {
            if (checkEleShow("#productNameDiv")) {
                return $('input[name="quoteProduct"]:checked').val();
            } else {
                return null;
            }
        },
    };

    var getters = {
        getInputValueById: function(id) {
            return $.trim($("#" + id).val());
        },
        getTelephoneById: function(id) {
            let $telephone = $("#" + id);
            if ($telephone.length > 0 && $telephone.val().indexOf("*") > 0) {
                return $telephone.data('real-val');
            } else {
                return $telephone.val()
            }
        },
        getTelephone: function() {
            let $telephone = $("#telephone");
            if ($telephone.length > 0 && $telephone.val().indexOf("*") > 0) {
                return $telephone.data('real-val');
            } else {
                return $telephone.val()
            }
        },
        getTelephone2: function() {
            let $telephone = $("#telephone2");
            if ($telephone.length > 0 && $telephone.val().indexOf("*") > 0) {
                return $telephone.data('real-val');
            } else {
                return $telephone.val()
            }
        },
        getTelephone3: function() {
            let $telephone = $("#telephone3");
            if ($telephone.length > 0 && $telephone.val().indexOf("*") > 0) {
                return $telephone.data('real-val');
            } else {
                return $telephone.val()
            }
        },
        getLocation: function() {
            return {
                lng: $("#longitude").val(),
                lat: $("#latitude").val(),
            };
        },
        getLongitude: function() {
            return $("#longitude").val();
        },
        getLatitude: function() {
            return $("#latitude").val();
        },
        getPlat: function() {
            return $("#plat").val() || plat;
        },
        getPlatWork: function() {
            return $("#platWork").val() || $("#plat").val() || platMark.ZMN;
        },
        getType: function() {
            return $("#type").val();
        },
        getProvinceId: function() {
            return getLayuiSelectValue("#provinceId");
        },
        getProvinceName: function() {
            return getLayuiSelectText("#provinceId");
        },
        getCityId: function() {
            return getLayuiSelectValue("#cityId");
        },
        getCityName: function() {
            return getLayuiSelectText("#cityId");
        },
        getCountyId: function() {
            return this.getInputValueById("countyId");
        },
        getInputCountyName: function() {
            let countyId = this.getCountyId();
            if (!countyId) return "";
            return $('#county-list').find('span[data-id=' + countyId + ']').text();
        },
        getStreetId: function() {
            return this.getInputValueById("streetId");
        },
        getCityName: function() {
            return $("#cityId option:selected").text();
        },
        getStreet: function() {
            return $("#customerAddress").val();
        },
        getStreetSource: function() {
            return $('#streetSource').val() || 0;
        },
        getAddress: function() {
            return $('input[name="address"]').val();
        },
        getServCategId: function() {
            return getLayuiSelectValue("#servCategoryId0");
        },
        getProductShowType: function() {
            return $('input[name="productShowType0"]:checked').val() || 2;
        },
        getProductId: function() {
            if (getters.getProductShowType() == "1") {
                return getLayuiSelectValue("#product0");
            } else {
                return getLayuiSelectValue("#showProduct0");
            }
        },
        getChannelId: function() {
            if ($("#type").val() == "2") {
                // 返修
                return $("#sourceChannelId").val();
            } else {
                // 新单
                return getLayuiSelectValue("#channelId");
            }
        },
        getChannelName: function() {
            return getLayuiSelectText("#channelId");
        },
        getBizType: function() {
            return $("#bizType").val() || BIZ_TYPE.C;
        },
        getDutyTime: function() {
            return $("#duty-time-input").val();
        },
        getWorkId: function() {
            return $("#work-id").val();
        },
        getOrderId: function() {
            return $("#order-id").val();
        },
        getCount: function() {
            var count = $("#count").val();
            return Number.parseInt(count) || 0;
        },
        getOrderType: function() {
            return this.getInputValueById("type");
        },
        getReworkId: function() {
            return this.getInputValueById("reworkId");
        },
        getEquityType: function() {
            return $('input[name="equityType"]:checked').val();
        },
        getServItemType: function() {
            return this.getInputValueById("servItemType");
        },
        getBrandId: function() {
            if (getters.getReceiveEntranceId() == '1002') {
                return getLayuiSelectValue("#brand");
            }
            return getLayuiSelectValue("#brand") || 1051;
        },
        getTest: function() {
            return $('input[name="test"]:checked').val() || 1;
        },
        getRemark: function() {
            return $('#remark').val();
        },
        getReceiveEntranceId: function() {
            return $('#receiveEntranceId').val();
        },
        getCallId: function() {
            return $('#callId').val();
        },
        getClueId: function() {
            return $('#clueId').val();
        },
        getUserName: function() {
            return $('#userName').val();
        },
        getGender: function() {
            return $("input[name='gender']:checked").val();
        },
        isCheckRealPhone: function (){
            var isRealPhone = $("#isRealPhone").val();
            var callId = $("#callId").val();
            if (isRealPhone != 2 || !callId) {
                return false;
            }
            return true;
        },
        getCommonRemarkList: function() {
            let remarkArr = [];
            $("input[name='commonRemark']:checked").each(function (index, item) {
                remarkArr.push({
                    id: $(item).val(),
                    name: $(item).attr("title")
                })
            });
            return remarkArr;
        },
        getExternalShopInfo: function() {
            if (!options.enableExternalShop) {
                return null;
            }
            let valueArr = zmnOmsSelect.getXmSelect('externalShopInfo').getValue();
            if (!valueArr) {
                return null;
            }
            if (valueArr < 1) {
                return null;
            }
            return {
                internalShopId: valueArr[0].internalShopId,
                internalShopName: valueArr[0].internalShopName,
                internalBranchShopName: valueArr[0].internalBranchShopName,
                externalShopId: valueArr[0].externalShopId
            };
        },
        getRequestId : function () {
            return $("#requestId").val();
        }
    };

    /**
     * 接收优惠批次ID集合
     */
    window.setDiscountInfo = function(obj) {
        // 获取当前手机号对应的数组（防止修改过手机号，优惠券发放给错误用户）
        let discountInfoMap = discountTelephoneMap.get(getters.getTelephone());
        if (!discountInfoMap) {
            // 当前手机号优惠信息
            discountInfoMap = new Map();
            discountTelephoneMap.set(getters.getTelephone(), discountInfoMap);
        }
        // 获取当前产品index
        let discountProIdxInfoMap = discountInfoMap.get(currProductIndex);
        if (!discountProIdxInfoMap) {
            // 当前产品idx 以备后期多产品发放优惠券
            discountProIdxInfoMap = new Map();
            discountInfoMap.set(currProductIndex, discountProIdxInfoMap);
        }
        // 处理CheckBox选中值
        if (obj.sendCoupFlg) {
            obj.sendCoupFlg = 2;
        } else {
            obj.sendCoupFlg = 1;
        }

        let key = "" + obj.batchId + "-" + obj.activityId;

        discountProIdxInfoMap.set(key, obj);
    };

    /**
     * 接收优惠批次ID集合
     */
    function setBestDiscountInfo(index, obj) {
        // 获取当前手机号对应的数组（防止修改过手机号，优惠券发放给错误用户）
        let discountInfoMap = bestDiscountTelephoneMap.get(getters.getTelephone());
        if (!discountInfoMap) {
            // 当前手机号优惠信息
            discountInfoMap = new Map();
            bestDiscountTelephoneMap.set(getters.getTelephone(), discountInfoMap);
        }
        // 获取当前产品index
        let discountProIdxInfoMap = discountInfoMap.get(index);
        if (!discountProIdxInfoMap) {
            // 当前产品idx 以备后期多产品发放优惠券
            discountProIdxInfoMap = new Map();
            discountInfoMap.set(index, discountProIdxInfoMap);
        }
        // 处理CheckBox选中值
        if (!obj.sendCoupFlg) {
            obj.sendCoupFlg = 2;
        }

        let key = "" + obj.batchId + "-" + obj.activityId;

        discountProIdxInfoMap.set(key, obj);
    };

    function clearCurrDiscountInfo(index) {
        // 获取当前手机号对应的数组（防止修改过手机号，优惠券发放给错误用户）
        let discountInfoMap = discountTelephoneMap.get(getters.getTelephone());
        if (discountInfoMap) {
            // 当前手机号优惠信息
            let discountProIdxInfoMap = discountInfoMap.set(index, new Map());

            // 刷新优惠信息
            reloadProductDiscount(key);
        }
    }

    function clearAllProductDiscountInfo(channelId, cityId, productId) {
        // 获取当前手机号对应的数组
        let discountInfoMap = discountTelephoneMap.get(getters.getTelephone());

        // 清空
        discountTelephoneMap.set(getters.getTelephone(), new Map());

        // 重新获取优惠
        if (discountInfoMap) {
            for (var key of discountInfoMap.keys()) {
                reloadProductDiscount(key, channelId, cityId, productId);
            }
        }
    }

    function reloadProductDiscount(index, channelId, cityId, productId) {
        // 获取当前产品价格信息
        var price = $("#amount" + index).data("price");
        reloadDiscountInfo(price, index, true, channelId, cityId, productId);
    }

    function reloadAdvanceQuoteDiscount() {
        setTimeout(function () {
            if (!checkEleShow('#quoteTypeDiv')) {
                return;
            }

            $("#discount-wrapper0").show();

            // 判断当前是否需要根据报价产品生成价格
            let channelId = getters.getChannelId();
            let cityId = getters.getCityId();
            if (checkEleShow('#productNameDiv')) {
                // 显示

                // 获取当前产品价格信息
                let $product = $('input[name="quoteProduct"]:checked');
                let price = $product.data("price");

                reloadDiscountInfo(price, 0, true, channelId, cityId);
            } else {
                // 隐藏
                reloadDiscountInfo(0, 0, true, channelId, cityId);
            }
        }, 500);
    }


    /**
     * 重新加载优惠相关信息
     */
    function resetDiscountInfoWithNoPrice(index) {
        // 隐藏勾选最大优惠 并设置checkBox为未选中
        $("#send-discount-checkbox" + index).attr("checked", false);
        form.render();
        $("#send-discount-checkbox" + index).parent().parent().hide();

        $("#used-discount" + index).text("工程师确认价格后系统自动使用").parent().show();
    }

    function reloadDiscountInfo(price, index, isShow, channelId, cityId, productId, showType) {
        if (!price || price === 0) {
            resetDiscountInfoWithNoPrice(index);
            return;
        }
        // 渠道id
        if (!channelId) {
            channelId = getters.getChannelId();
            if (!channelId) {
                return;
            }
        }

        // 城市id
        if (!cityId) {
            cityId = getters.getCityId();
            if (!cityId) {
                return;
            }
        }

        // 产品id
        if (!productId) {
            productId = newGetters.getProductId(index);
            if (!productId) {
                return;
            }
        }

        // 产品类型
        if (!showType) {
            showType = newGetters.getProductShowType(index);
            if (!showType) {
                return;
            }
        }

        // 批次集合
        let batchListJson = "";
        if (discountTelephoneMap.get(getters.getTelephone()) && discountTelephoneMap.get(getters.getTelephone()).get(index)) {
            let batchList = Array.from(discountTelephoneMap.get(getters.getTelephone()).get(index).values()).map((batch) => JSON.stringify(batch));
            batchListJson = "[" + batchList.join(",") + "]";
        }
        // 查询无用户优惠信息
        $http
            .$get(GET_ADD_ORDER_DISCOUNT_URL, {
                telephone: getters.getTelephone(),
                channelId: channelId,
                cityId: cityId,
                brandId: newGetters.getBrandId(index),
                productId: productId,
                productNum: newGetters.getCount(index),
                showType: showType,
                bizType: getters.getBizType(),
                servItemType: $("#servItemType" + index).val(),
                platWork: getters.getPlatWork(),
                plat: getters.getPlat(),
                type: getters.getType(),
                price: price,
                batchListJson: batchListJson,
                receiveEntranceId: getters.getReceiveEntranceId(),
            })
            .then(
                function(data) {
                    reloadUseDiscountInfo(data, index, isShow);
                    reloadMaxDiscountInfo(data, index, isShow);

                    // 缓存最佳优惠组合
                    if (data.bestDiscountList) {
                        var bestDiscountList = data.bestDiscountList;
                        for (let i = 0; i < bestDiscountList.length; i++) {
                            setBestDiscountInfo(index, bestDiscountList[i]);
                        }
                    }

                },
                function(msg) {
                    layer.msg(msg);
                }
            );
    }

    /**
     * 获取当前优惠（不发放优惠券即可使用）
     */
    function reloadUseDiscountInfo(data, index, isShow) {
        if (isShow) {
            $("#used-discount" + index).text("当前优惠 -" + data.currentPreferential / 100 + "元\n 优惠后价格 " + data.afterPrice / 100 + "元").parent().show();
        } else {
            $("#used-discount" + index).parent().hide();
        }
    }

    /**
     * 获取最大可用优惠（包含优惠券）
     */
    function reloadMaxDiscountInfo(data, index, isShow) {
        if (isShow && data.bestPreferential > data.currentPreferential) {
            $("#send-discount-checkbox" + index).prop("title", "查询到最佳优惠" + data.bestPreferential / 100 + "元，优惠后价格" + data.afterBestPrice / 100 + "元，勾选后使用");
            form.render();
            // 修改字体颜色
            $("#send-discount-checkbox" + index).parent().find("span").css("color", "red");
            $("#send-discount-checkbox" + index).parent().parent().show();
        } else {
            $("#send-discount-checkbox" + index).parent().parent().hide();
        }
    }

    /**
     * 渲染服务品类选择下拉框
     * @param data 下拉框数据
     */
    function renderProductSelect(data, elment, index) {
        var htmlStr = '<option value=""></option>';

        $.each(data, function(index, item) {
            var price = item.price || item.originalPrice;
            var productName;

            if (price) {
                productName = item.text + "_" + price + "_" + item.unit;
            } else {
                productName = item.text;
            }

            htmlStr +=
                '<option value="' +
                item.value +
                '" data-price="' +
                (price ? price : "") +
                '" data-unit="' +
                (item.ext1 || "") +
                '" data-type="' +
                item.type +
                '" data-pid="' +
                item.pid +
                '">' +
                productName +
                "</option>";
        });

        $(elment).html(htmlStr);
        var str = "servCategoryA" + index;
        form.render("select", str);
    }

    /**
     *  初始化产品下拉框
     * @param {string} servCategId 服务分类id
     */
    function initProduct(switchShowType, selectServCategory, index, value) {
        var plat = getters.getPlat();
        var servCategId = index ?
            getLayuiSelectValue("#servCategoryId" + index) :
            getLayuiSelectValue("#servCategoryId0");
        var productShowType =
            $('input[name="productShowType' + index + '"]:checked').val() || 2 || "";
        var cityId = getters.getCityId();
        var channelId = getters.getChannelId();
        var bizType = getters.getBizType();

        if (!plat || !productShowType || !cityId || !channelId) {
            return;
        }
        initProductSelect(
            plat,
            servCategId,
            productShowType,
            cityId,
            channelId,
            switchShowType,
            selectServCategory,
            bizType,
            index
        ).always(function() {
            // 计算价格
            calculateProductAmount(index);

            // 处理提前付逻辑
            checkAdvanceQuote();
        });
    }

  function initDutyTime(index, callback) {
    if (!options.isNew) {
      if (callback) callback();
      return;
    }

    if (!getters.getLongitude() || !getters.getLatitude()) {
        if (callback) callback();
        return;
    }

    setTimeout(getProductId, 300);
    function getProductId() {
      if (!newGetters.getProductId(index)) {
        if (callback) callback();
        return;
      }
      $("#gird-group-distribute-master" + index).text('');

      var productId = getLayuiSelectValue("#product" + index);
      var showProductId = getLayuiSelectValue("#showProduct" + index)

      $http
          .$get(GET_DEFAULT_DUTYTIME, {
            dutyTime: newGetters.getDutyTime(index),
            plat: getters.getPlat(),
            platWork: getters.getPlatWork(),
            channelId: getters.getChannelId(),
            cityId: getters.getCityId(),
            productId: productId,
            showProductId: showProductId,
            type: getters.getOrderType(),
            latitude: getters.getLatitude(),
            longitude: getters.getLongitude(),
            isGrid: isGrid,
            productNum: newGetters.getCount(index),
            servCategId: newGetters.getServCategId(index),
            bizType: getters.getBizType(),
          })
          .then(
              function (data) {
                isAvailableWeeks[index] = data.isAvailableWeek;
                if (data.girdGroupDistributeShowStr) {
                  //网格组派单结果展示回显
                  initDutyTimeInfo("", "", index);
                  $("#gird-group-distribute-master" + index).text(data.girdGroupDistributeShowStr);
                }else {
                  $("#gird-group-distribute-master" + index).text('');
                  initDutyTimeInfo(data.showDutyTime, data.dutyTime, index, data.isToday);
                }
                if (callback) callback();
              },
              function (msg) {
                layer.msg("获取默认时间失败");
                initDutyTimeInfo("", "", index);
                if (callback) callback();
              }
          );
    }
  }

  /**
   * 初始化全部预约时间
   */
  function initAllDutyTime() {
    const list = window.EventBus.list;
    list.forEach(function (el, index) {
      if (window.EventBus.checkRemove(index)) {
        initDutyTime(index);
      }
    });
  }

  /**
   * 清理全部预约时间
   */
  function clearAllDutyTime() {
    const list = window.EventBus.list;
    list.forEach(function (el, index) {
      if (window.EventBus.checkRemove(index)) {
        clearDutyTime(index);
      }
    });
  }

  function clearDutyTime(index){
    initDutyTimeInfo("", "", index);
    $("#gird-group-distribute-master" + index).text('');
  }


    /**
     * 检查是否是真实手机号
     */
    function checkRealPhoneAndSaveOrder(ret, params, btn) {
        // 查询真是手机号
        var isRealPhone = $("#isRealPhone").val();
        var callId = $("#callId").val();
        if (isRealPhone == 2) {
            if (!callId) {
                beforeSaveOrder(params, btn);
                return;
            }
            $http.get(GET_REAL_PHONE_URL, {
                callId: callId
            }).then(
                function(data) {
                    if (data) {
                        if (ret) {
                            params.telephone = data.realPhone;
                            beforeSaveOrder(params, btn);
                        } else {
                            $("#telephone").val(data.hidePhone);
                            $("#telephone").attr("data-val", data.hidePhone);
                            $("#telephone").attr("data-real-val", data.realPhone);
                            $("#isRealPhone").val(2);
                        }
                    }
                },
                function(msg) {
                    layer.msg(msg);
                }
            );
        } else {
            beforeSaveOrder(params, btn);
        }
    }

    /**
     * 获取真实号码
     */
    function initRealPhone(callback) {
        let callId = $("#callId").val();
        // 查询真是手机号
        $http.get(GET_REAL_PHONE_URL, {
            callId: callId
        }).then(
            function(data) {
                let $telephone = $("#telephone");
                $telephone.val(data.hidePhone);
                $telephone.data("val", data.hidePhone);
                $telephone.data("real-val", data.realPhone);
                isRealCallTelephone = true;
                if (callback) {
                    callback(data.realPhone);
                }
            },
            function(msg) {
                isRealCallTelephone = false;
                layer.msg(msg);
            }
        );
    }

    function initProductSelect(
        plat,
        servCategId,
        productShowType,
        cityId,
        channelId,
        switchShowType,
        selectServCategory,
        bizType,
        index
    ) {
        index;
        $("#dv-show-product" + index).removeClass("layui-hide");
        $("#dv-product" + index).removeClass("layui-hide");
        //($("#dv-show-product" + index));
        var elment;
        var cacheData;
        var cacheKey = servCategId + "-" + cityId + "-" + channelId + "-" + bizType;
        //(cacheKey);
        // alert("productShowType=" + productShowType);
        if (productShowType == "1") {
            elment = "#product" + index;
            $("#dv-show-product" + index).addClass("layui-hide");
            cacheData = productCache[cacheKey];
        } else {
            elment = "#showProduct" + index;
            $("#dv-product" + index).addClass("layui-hide");
            cacheData = showProductCache[cacheKey];
        }

        // 记录上一次选中的值
        var perProductId = getLayuiSelectValue(elment);
        var perProductText = getLayuiSelectText(elment);
        // alert(perProductId);
        // 前后端产品切换过来的，有值不加载数据
        if (switchShowType) {
            if (getLayuiSelectValue(elment)) {
                return $.Deferred().resolve();
            }
        }
        // 其他方式加载的，全部清空
        else {
            renderProductSelect([], "#product" + index, index);
            renderProductSelect([], "#showProduct" + index, index);
        }
        //(cacheData);

        if (cacheData) {
            renderProductSelect(cacheData, elment, index);

            // 默认选中上一个产品
            $(elment).val(perProductId);
            var str = "servCategoryA" + index;
            form.render("select", str);

            // 如果没有合适的产品，提示 当前渠道未开通：xx产品，请重新选择产品
            if (!getLayuiSelectValue(elment) &&
                perProductId &&
                selectServCategory !== 1
            ) {
                zmnUtils.layui.toastError(
                    "当前渠道未开通：" + perProductText + "，请重新选择产品"
                );
            }

            return $.Deferred().resolve();
        } else {
            productShowType;
            return fetchProductData(
                plat,
                servCategId,
                productShowType,
                cityId,
                channelId,
                bizType,
                index
            ).then(
                function(data) {
                    //($(elment));
                    renderProductSelect(data, elment, index);

                    if (productShowType == "1") {
                        productCache[cacheKey] = data;
                    } else {
                        showProductCache[cacheKey] = data;
                    }

                    // 默认选中上一个产品
                    $(elment).val(perProductId);
                    var str = "servCategoryA" + index;
                    form.render("select", str);

                    if (!getLayuiSelectValue(elment) &&
                        perProductId &&
                        selectServCategory !== 1
                    ) {
                        zmnUtils.layui.toastError(
                            "当前渠道未开通：" + perProductText + "，请重新选择产品"
                        );
                    }
                },
                function(msg) {
                    layer.msg("产品数据获取失败");
                    renderProductSelect([], elment, index);
                }
            );
        }
    }

    /**
     * 初始化产品数量输入框
     * @param {string} value 产品数量
     */
    function initCountInput(value, index) {
        var $input = $("#count" + index);
        $input.val(value);
    }

    /**
     * 初始化产品数量
     * @param {string} text 产品单位
     */
    function initProductUnit(text, index) {
        $("#unit" + index).text(text);
    }

    /**
     * 初始化品牌下拉框
     * @param {string} value 初始值
     */
    function initBrandSelect(value, index) {
        $("#brand" + index).val(value);
        var str = "servCategoryA" + index;
        form.render("select", str);
    }

    /**
     * 渲染常见错误多选框组
     * @param data 下拉框数据
     */
    function renderFaultsCheckboxGroup(data, index) {
        var htmlStr = "";
        var $faultsGroup = $("#faults-wrapper" + index);
        var $faultsRow = $faultsGroup.closest(".layui-form-item");
        const nameIndex = index;
        $.each(data, function(index, item) {
            htmlStr +=
                '<input type="checkbox" lay-skin="primary" name="faultIdList' +
                nameIndex +
                '" title="' +
                item.text +
                '" value="' +
                item.value +
                '" >';
        });

        $faultsGroup.html(htmlStr);

        if (data.length) {
            $faultsRow.show();
        } else {
            $faultsRow.hide();
        }

        form.render("checkbox");
    }

    /**
     * 初始化常见故障多选框组
     * @param {string} productId 产品id
     */
    function initCommonFaultsCheckboxGroup(productId, index) {
        // 判断是否需要报价，如果需要，不显示
        if (checkEleShow("#quoteTypeDiv")) {
            return;
        }
        if (!productId) {
            renderFaultsCheckboxGroup([], index);
        } else {
            fetchProductSubsidiary(productId).then(function(data) {
                renderFaultsCheckboxGroup(data, index);
            });
        }

        // 初始化其他故障文本域
        //initOtherFaultsTextarea("", index);
    }

    /**
     * 初始化其他故障文本框
     * @param {string} value 初始值
     */
    function initOtherFaultsTextarea(value, index) {
        $("#fault-remark" + index).val(value);
    }

    /**
     * 更新下拉框选项的状态。1. 当前元素不可点击 2. 其余可以选项可以点击
     * @param elem select dom 元素
     */
    function updateOptionsStatus(elem, index) {
        $(elem)
            .find("option")
            .attr("disabled", false)
            .filter(":selected")
            .attr("disabled", true);
        if (index >= 0) {
            form.render("select", "servCategoryA" + index);
        } else {
            form.render("select", "adress");
        }
    }

    /**
     * 渲染下拉选择框
     * @param el
     * @param data 下拉框数据
     * @param defaultVal 默认值
     */
    function renderSelect(el, data, defaultValue, layFormSelect) {
        defaultValue;
        var htmlStr = '<option value=""></option>';
        //(data);
        $.each(data, function(index, item) {
            htmlStr +=
                '<option value="' +
                item.value +
                '" ' +
                (item.value == defaultValue ? " selected " : "") +
                ">" +
                item.text +
                "</option>";
        });
        $(el).html(htmlStr);
        //(layFormSelect);
        form.render("select", layFormSelect);
    }

    /**
     * 渲染城市选择下拉框
     * @param {array} data 城市数据
     */
    function renderCitySelect(data) {
        var htmlStr = '<option value=""></option>';

        var oldCityId = getters.getCityId();
        var oldCityName = getLayuiSelectText("#cityId");

        $.each(data, function(index, item) {
            htmlStr +=
                '<option value="' +
                item.value +
                '" data-pid="' +
                item.pid +
                '" ' +
                (oldCityId == item.value ? "selected " : " ") +
                ">" +
                item.text +
                "</option>";
        });
        $("#cityId").html(htmlStr);
        form.render("select");

        var result = $.grep(data, function(e) {
            return e.value == oldCityId;
        });
        if (
            showCheckCityMsg &&
            options.isNew &&
            oldCityName != "" &&
            oldCityName != "市" &&
            result.length == 0
        ) {
            // 若未开通，清空：地址
            var cityName = getLayuiSelectText("#cityName");
            clearAddress();
            zmnUtils.layui.toastError(
                "当前渠道未开通：" + oldCityName + "，请重新选择城市"
            );
        }
    }

    /**
     * 渲染城市选择下拉框
     * @param provinceId 省份ID
     */
    function initCitySelect(provinceId, channelId, showMsg, cb) {
        showCheckCityMsg = showMsg;

        var key = provinceId;
        if (options.isNew) {
            key = (provinceId || 0) + "-" + channelId;
        } else {
            // provinceId 为空时执行
            if (!provinceId) {
                renderCitySelect(json.cityList);
                if (cb) {
                    cb();
                }
                return;
            }
        }

        if (cityData[key]) {
            renderCitySelect(cityData[key]);
            if (cb) {
                cb();
            }
        } else {
            fetchCityData(provinceId).done(function(data) {
                cityData[key] = data;
                renderCitySelect(data);
                if (cb) {
                    cb();
                }
            });
        }
    }

    /**
     * 初始化服务区域显示
     * 初始化区县下拉框
     * @param {array} data 服务区域列表
     */
    function renderServiceArea(data, cb) {
        var htmlStr = "";

        countyData = [];
        $.each(data, function(index, county) {
            if (!county.disabled) {
                htmlStr += `<span class="county" data-id="${county.value}">${county.text}</span>`;
                countyData.push({
                    countyId: county.value,
                    countyName: county.text
                })
            }
        });

        var $serviceArea = $("#county-list");
        $serviceArea.html(htmlStr);

        var $countyId = $("#countyId");
        var optionHtmlStr = '<option value="">请选择区县</option>';

        var countyId = $countyId.val();
        $.each(data, function(index, county) {
            if (!county.disabled) {
                if (countyId && county.value == countyId) {
                    optionHtmlStr += `<option value="${county.value}" selected="selected">${county.text}</option>`;
                } else {
                    optionHtmlStr += `<option value="${county.value}">${county.text}</option>`;
                }
            }
        });

        $countyId.html(optionHtmlStr);
        form.render("select");

        if (data.length) {
            $serviceArea.show();
        } else {
            $serviceArea.hide();
        }

        if (typeof cb === "function") {
            cb();
        }

        updateAreaList(getters.getCountyId());
    }

    /**
     * 清空街道信息
     */

    /**
     * 初始化街道显示
     */
    function renderStreetIdSelect(data, cb) {
        var optionHtmlStr = '<option value="">请选择乡镇或街道</option>';

        var streetId = $("#streetId").val();
        $.each(data, function(index, street) {
            optionHtmlStr += `<option value="${street.areaId}" data-longitude="${street.longitude}" data-latitude="${street.latitude}">${street.name}</option>`;
        });

        $("#streetId").html(optionHtmlStr);
        form.render("select");

        if (typeof cb === "function") {
            cb();
        }
    }

    /**
     * 初始化服务区域显示
     */
    function initServiceArea(cityId, cb) {
        var cityId = cityId || getters.getCityId();

        if (!cityId) {
            renderServiceArea([]);
            return;
        }

        fetchAreaData(cityId).done(function(data) {
            renderServiceArea(data, cb);
        });
    }

    /**
     *  生成街道地址下拉框列表项
     * @param {Object} data 街道地址数据
     * @returns {string}
     */
    function createfetchSuggestedItemHtmlStr(data) {
        data.district = data.district || '';
        return (
            '<li data-lng="' + data.location.lng +
            '" data-lat="' + data.location.lat +
            '" data-communityid="' + (data.communityId || 999999) +
            '" data-source="' + (data.source || 2) +
            '" data-city="' + data.city +
            '" data-district="' + data.district +
            '" data-name="' + data.name + '">' +
            data.name +
            '<span class="city-district">' +
            data.city + data.district +
            "</span>" +
            "</li>"
        );
    }

    /**
     *  渲染街道列表下拉框
     * @param params 联想参数
     */
    function renderStreetSelect(params) {
        $("#suggestPanel ul").html('<li class="loading tip">加载中</li>');
        fetchSuggestedStreet(params, function(data) {
            var htmlStr = "";

            if (data.length) {
                $.each(data, function(index, item) {
                    htmlStr += createfetchSuggestedItemHtmlStr(item);
                });
            } else {
                htmlStr += '<li class="non-data tip">无匹配项</li>';
            }

            layer.open({
                area: ["0", "0"],
                shade: [0.1, "#fff"],
                offset: ["100000px", "100000px"],
                scrollbar: false,
                zIndex: 888,
                success: function(layero, index) {
                    $("#layui-layer-shade" + index).on("click", function() {
                        $(layero).find(".layui-layer-close").trigger("click");
                    });
                },
                cancel: function() {
                    $("#suggestPanel").hide();
                    clearAddress();
                },
            });
            $("#suggestPanel ul").html(htmlStr);
            $("#suggestPanel").show();
            // form.render('select');

            // $('#street-wrapper').find('.layui-form-select').addClass('layui-form-selected');
            // $('#street-wrapper').find('input').val(queryText).focus();
        });
    }

    /**
     * 渲染服务类型选择下拉框
     */
    function renderServCategorySelect(callback, index) {
        index;
        var cityId = getters.getCityId();
        var channelId = getters.getChannelId();
        var showType = newGetters.getProductShowType(index);
        var servCategId = newGetters.getServCategId(index);
        if (!cityId || !channelId) {
            //(1289);
            return;
        }

        var cacheKey = cityId + "-" + channelId + "-" + showType;
        //(servCategoryCache);
        if (servCategoryCache[cacheKey]) {
            //(123);
            renderSelect(
                index ? "#servCategoryId" + index : "#servCategoryId",
                servCategoryCache[cacheKey],
                servCategId,
                index ? "servCategory" + index : "servCategory0"
            );
            // 加载产品
            if (callback) {
                callback();
            }
        } else {
            $.getJSON(
                GET_SERV_CATEG_BY_CITY_CHANNEL_SHOWTYPE_URL, {
                    channelId: channelId,
                    cityId: cityId,
                    showType: showType,
                },
                function(rsp) {
                    index;
                    if (rsp.status === 200) {
                        //(567);
                        servCategoryData = rsp.data;
                        servCategoryCache[cacheKey] = servCategoryData;
                        renderSelect(
                            index ? "#servCategoryId" + index : "#servCategoryId0",
                            servCategoryData,
                            servCategId,
                            index ? "servCategory" + index : "servCategory0"
                        );
                    } else {
                        renderSelect(
                            index ? "#servCategoryId" + index : "#servCategoryId0", [],
                            "",
                            index ? "servCategory" + index : "servCategory0"
                        );
                    }
                    // 加载产品
                    if (callback) {
                        callback();
                    }
                }
            );
        }
    }

    /**
     * 设置分公司名
     * @param {string} name 公司名
     */
    function setCompanyInfo(name) {
        $("#company").html(name);
    }

    /**
     * 校验提前付试点
     */
    function checkAdvanceQuote() {
        if (window.EventBus.list.length > 1) {
            return;
        }

        let cityId = getters.getCityId();
        let servCategId = getters.getServCategId();
        let productId = newGetters.getProductId(0);
        let showProductType = newGetters.getProductShowType(0);
        if (!cityId || !productId || !showProductType) {
            hideAllAdvanceQuoteItem();
            return;
        }

        $http.$post(
            CHECK_ADVANCE_QUOTE_URL, {
                cityId: cityId,
                servCategId: servCategId,
                productId: productId,
                showProductType: showProductType,
            }).then(function (rsp) {
                // 请求成功, 2 开启试点
                let isAdvanceQuote = rsp == 2;
                // 初始化报价试点
                initAdvanceQuote(isAdvanceQuote);
            }
        );
    }

    /**
     * 约束只能选择前台产品
     */
    function initAdvanceQuote(isAdvanceQuote) {
        if (isAdvanceQuote) {
            let showType = newGetters.getProductShowType(0);
            if (showType == '1') {
                layer.msg("此产品符合提前付试点，请选择前台产品");
                form.render();
                return;
            }

            // 如果是前台产品 只禁用后台产品
            $('input[name=productShowType0][value="1"]').attr("disabled", "disabled");
            if (getters.getProductShowType() == '1') {
                // 切换到选择前台产品，并且禁用后台产品按钮
                $('input[name=productShowType0][value="2"]').prop("checked", "true");
                triggerLayuiEvent('input[name=productShowType0][value=2]', 'product-showtype');
                setTimeout(function (params) {
                    layer.msg("试点城市，仅支持选择前台产品");
                }, 500);
            }
            // 隐藏价格
            $("#amount-wrapper0").hide();
            $("#faultDiv").hide();
            // 隐藏新增产品按钮
            $("#addProduct").hide();
            // 显示报价方式选择框
            $("#quoteTypeDiv").show();
            // 显示发送短信按钮
            $("#sendOrderTransferFailMessageBtn").show();
            $("#sendOrderConfirmQuotedFailMessageBtn").show();

            // 初始化报价相关信息
            initAdvanceQuoteItem();
        } else {
            // 启用后台产品
            $('input[name=productShowType0][value="1"]').removeAttr("disabled");
            // 显示新增产品按钮
            $("#addProduct").show();
            // 隐藏发送短信按钮
            $("#sendOrderTransferFailMessageBtn").hide();
            $("#sendOrderConfirmQuotedFailMessageBtn").hide();
            if ($("faults-wrapper0").html()) {
                $("#faultDiv").show();
            }
            // 隐藏报价相关元素
            hideAllAdvanceQuoteItem();
        }

        // 刷新价格表

        loadAdvanceQuotePriceTable();

        form.render();
    }

    /**
     * 触发layui form.on事件
     */
    function triggerLayuiEvent(jqueryFilter, filter) {
        var elem = layui.$(jqueryFilter);
        var option = {
            elem:elem,
            value: elem.val(),
            othis: elem.next('layui-form-radio')
        }
        //layui.event(modName, events, params)	执行自定义模块事件，搭配 onevent 使用
        layui.event('form', 'radio('+ filter +')', option);
    }

    // 初始化报价相关内容
    function initAdvanceQuoteItem() {
        let cityId = getters.getCityId();
        let channelId = getters.getChannelId();
        let bizType = getters.getBizType();
        let platWork = getters.getPlatWork();
        let productId = newGetters.getProductId();
        let brandId = newGetters.getBrandIdWithoutDefaultVal();
        if (!cityId || !channelId || !productId) {
            hideAllAdvanceQuoteItem();
            return;
        }
        if (!brandId) {
            return;
        }

        // 获取报价相关信息
        $.ajax({
                url: GET_QUOTE_INFO_URL,
                type: "POST",
                data: JSON.stringify({
                    bizType: bizType,
                    channelId: channelId,
                    platWork: platWork,
                    cityId: cityId,
                    showProductId: productId
                }),
                processData: false,
                contentType: "application/json;charset=UTF-8",
                error: function () {
                    alert('获取信息失败');
                },
                success: function (rsp) {
                    if (rsp.status === 200) {
                        // 请求成功
                        let quoteInfo = rsp.data;
                        let brandId = newGetters.getBrandIdWithoutDefaultVal();
                        // 是否指定了使用某个报价信息
                        if (quoteInfo.faultPhenList) {
                            // 所有报价方式均可用，默认故障现象报价
                            $('input[name="quoteType"][value="1"]').removeAttr("disabled");
                            $('input[name="quoteType"][value="1"]').prop("checked", "true");
                            if (brandId) {
                                initFaultPhenList(quoteInfo.faultPhenList);
                            }
                        } else {
                            // 服务项报价
                            $('input[name="quoteType"][value="1"]').prop("disabled", "disabled");
                            $('input[name="quoteType"][value="2"]').prop("checked", "true");
                            if (brandId) {
                                initServiceItemList(quoteInfo.itemList);
                            }
                        }

                    }
                }
            }
        );
    }

    function initFaultPhenList(data) {
        let optionHtmlStr = "";
        var isChecked = data.length <= 1;
        let value ;
        $.each(data, function (index, phen) {
            value = phen.value;
            optionHtmlStr += `<input type="radio" lay-skin="primary" name="phenId"  value="${phen.value}" title="${phen.text}"`;
            if(isChecked) {
                optionHtmlStr += ` checked `
            }
            optionHtmlStr += `lay-filter="faultPhen"/>`;
        });

        $("#faultPhen").html(optionHtmlStr);
        form.render();

        $("#serviceItemDiv").hide();
        $("#faultPhenDiv").show();
        $("#productCategDiv").hide();
        $("#productNameDiv").hide();

        if(isChecked && value) {
            triggerLayuiEvent('input[name=phenId][value='+ value +']', 'faultPhen');
        }
    }
    function initServiceItemList(data) {
        var optionHtmlStr = '<option value="">请选择服务项目</option>';

        $.each(data, function(index, item) {
            optionHtmlStr += `<option value="${item.value}">${item.text}</option>`;
        });


        $("#serviceItem").html(optionHtmlStr);
        form.render();

        $("#serviceItemDiv").show();
        $("#faultPhenDiv").hide();
        $("#productCategDiv").hide();
        $("#productNameDiv").hide();
    }

    function initProductCateg(data) {
        if (data.length <= 0) {
            $("#productCategDiv").hide();
            $("#productNameDiv").hide();
            return;
        }
        var optionHtmlStr = "";
        var isChecked = data.length <= 1;
        let value ;
        $.each(data, function(index, categ) {
            let title = categ.categName + "  /  " + categ.minPrice / 100 + " ~ " + categ.maxPrice /100 + " 元";

            value = categ.categId;
            optionHtmlStr += ` <input type="radio"
                                    style="width:100%;"
                                           gotype="index"
                                           name="productCategId"
                                           value="${categ.categId}"
                                           title="${title}"`;
            if(isChecked) {
                optionHtmlStr += ` checked `
            }
            optionHtmlStr +=`lay-filter="productCateg">`;
        });

        $("#productCateg").html(optionHtmlStr);
        form.render();

        $("#productCategDiv").show();
        $("#productNameDiv").hide();

        if(isChecked && value) {
            triggerLayuiEvent('input[name=productCategId][value='+ value +']', 'productCateg');
        }
    }
    function initQuoteProduct(data) {
        var optionHtmlStr = "";
        var isChecked = data.length <= 1;
        $.each(data, function (index, product) {
            let title = product.tariffName + "  /  " + product.price / 100 + " 元";

            optionHtmlStr += ` <input type="radio"
                                    style="width:100%;"
                                           gotype="index"
                                           name="quoteProduct"
                                           value="${product.productId}"
                                           title="${title}"
                                           data-item-id="${product.itemId}"
                                           data-price="${product.price}"`;
            if (isChecked) {
                optionHtmlStr += ` checked `;
            }
            optionHtmlStr += `lay-filter = "quoteProduct" > `;
        });

        $("#quoteProduct").html(optionHtmlStr);
        form.render();

        $("#productNameDiv").show();

        if (data.length === 1) {
            triggerLayuiEvent('input[name="quoteProduct"]:checked', 'quoteProduct');
        }

    }

    function fetchProductCateg(phenId, itemId) {
        if (!phenId && !itemId) {
            $("#productCategDiv").hide();
            $("#productNameDiv").hide();
            return;
        }

        let cityId = getters.getCityId();
        let channelId = getters.getChannelId();
        let bizType = getters.getBizType();
        let platWork = getters.getPlatWork();
        let servCategId = newGetters.getServCategId();
        let productId = newGetters.getProductId();
        let brandId = newGetters.getBrandIdWithoutDefaultVal();
        if (!cityId || !channelId || !servCategId || !productId || !brandId) {
            return;
        }

        let requestUrl;
        let data = {
            bizType: bizType,
            channelId: channelId,
            platWork: platWork,
            cityId: cityId,
            showProductId: productId,
            itemId: itemId,
            brandId: brandId
        };
        if (phenId) {
            data.phenId = phenId;
            requestUrl = LIST_PRODUCT_CATEG_WITH_PHEN_ID_URL;
        } else if (itemId) {
            data.itemId = itemId;
            requestUrl = LIST_PRODUCT_CATEG_WITH_ITEM_ID_URL;
        } else {
            return;
        }

        // 服务项获取产品二级分类
        $.ajax({
                url: requestUrl,
                type: "POST",
                data: JSON.stringify(data),
                processData: false,
                contentType: "application/json;charset=UTF-8",
                error: function () {
                    alert('获取信息失败');
                },
                success: function (rsp) {
                    if (rsp.status === 200) {
                        // 请求成功
                        if (rsp.data) {
                            initProductCateg(rsp.data);
                        }

                    }
                }
            }
        );
    }

    function loadAdvanceQuotePriceTable(productId) {

        setTimeout(function () {
            var cityId = getters.getCityId();
            var productShowType;
            if (!productId) {
                productId = newGetters.getProductId(0);
                productShowType = newGetters.getProductShowType(0);

            }
            var channelId = getters.getChannelId();
            var bizType = getters.getBizType();
            var type = getters.getType();
            var plat = getters.getPlat();
            var brandId = newGetters.getBrandIdWithoutDefaultVal();

            if (!channelId || !cityId || !productId || !brandId) {
                $("#advanceQuotePrice").hide();
                return;
            }
            let productCategId = newGetters.getProductCateg();
            let itemId = newGetters.getItemId();
            let phenId = newGetters.getPhenId();
            let phenName = newGetters.getPhenName();

            if (!itemId && !phenId) {
                $("#advanceQuotePrice").hide();
                return;
            }
            $("#advanceQuotePrice").show();

            let priceTableURL;
            if (phenId) {
                let showProductId = newGetters.getProductId();
                let backProductId = newGetters.getQuoteProductId();
                priceTableURL = zmnUtils.serializeURL(ADVANCE_PRODUCT_PHEN_PRICE_TABLE_URL, {
                    cityId: cityId,
                    productId: showProductId,
                    channelId: channelId,
                    bizType: bizType || 1, // 默认保外
                    brandId: brandId,
                    tariffType: productShowType,
                    type: type,
                    plat: plat,
                    categId: productCategId,
                    phenId: phenId,
                    backProductId: backProductId
                });
                priceTableURL += "&phenName=" + phenName;
            } else {

                // 判断是否已选后台产品，如果已选择，覆盖为后台产品
                if (!productId && checkEleShow("#productNameDiv")
                    && $('input[name="quoteProduct"]:checked').val()) {
                    productId = $('input[name="quoteProduct"]:checked').val();
                    productShowType = 1;
                }
                priceTableURL = zmnUtils.serializeURL(ADVANCE_PRODUCT_PRICE_TABLE_URL, {
                    cityId: cityId,
                    productId: productId,
                    channelId: channelId,
                    bizType: bizType || 1, // 默认保外
                    brandId: brandId,
                    tariffType: productShowType,
                    type: type,
                    plat: plat,
                    itemId: itemId,
                    categId: productCategId
                });
            }

            $("#advanceQuotePriceTable").prop("src", priceTableURL);
        }, 500);
    }

    // 隐藏提前报价相关显示框
    function hideAllAdvanceQuoteItem() {
        $("#quoteTypeDiv").hide();
        $("#serviceItemDiv").hide();
        $("#faultPhenDiv").hide();
        $("#productCategDiv").hide();
        $("#productNameDiv").hide();
    }

    // 检验某个元素是否显示
    function checkEleShow(filter) {
        return $(filter).length > 0 && $(filter).css("display") != "none";
    }

    function initAdvanceQuoteEvent() {
        form.on("radio(quoteType)", function (data) {
            let cityId = getters.getCityId();
            let channelId = getters.getChannelId();
            let servCategId = newGetters.getServCategId(0);
            let bizType = getters.getBizType();
            let productId = newGetters.getProductId();
            let platWork = getters.getPlatWork();
            let quoteType = data.value;
            let brandId = newGetters.getBrandIdWithoutDefaultVal();
            if (!cityId || !channelId || !servCategId || !productId || !brandId) {
                $("#serviceItemDiv").hide();
                $("#faultPhenDiv").hide();
                $("#productCategDiv").hide();
                $("#productNameDiv").hide();
                if(!brandId) {
                    layer.msg('请选择品牌');
                    $(this).removeAttr("checked")
                    form.render();
                }
                return;
            }

            let requestURL = "";
            let callback ;
            if (quoteType == "1") {
                // 故障现象报价
                requestURL = LIST_PHEN_URL;
                callback = function (data) {
                    initFaultPhenList(data);
                }
            } else {
                // 服务项报价
                requestURL = LIST_SERVICE_ITEM_URL;
                callback = function (data) {
                    initServiceItemList(data);
                }
            }

            // 服务项获取产品二级分类
            $.ajax({
                    url: requestURL,
                    type: "POST",
                    data: JSON.stringify({
                        bizType: bizType,
                        channelId: channelId,
                        platWork: platWork,
                        cityId: cityId,
                        showProductId: productId,
                        brandId: brandId
                    }),
                    processData: false,
                    contentType: "application/json;charset=UTF-8",
                    error: function () {
                        alert('获取信息失败');
                    },
                    success: function (rsp) {
                        if (rsp.status === 200) {
                            // 请求成功
                            callback(rsp.data);
                        } else {
                            layer.msg(rsp.message);
                        }
                    }
                }
            );

            // 初始化价格表
            // loadAdvanceQuotePriceTable();
            $("#advanceQuotePrice").hide();
        });

        form.on("select(serviceItem)", function (data) {
            let itemId = data.value;
            fetchProductCateg(null, itemId, null);

            // 初始化价格表
            loadAdvanceQuotePriceTable();

            // 重新加载报价产品优惠信息
            reloadAdvanceQuoteDiscount();
        });
        form.on("radio(faultPhen)", function (data) {
            let phenId = data.value;
            if (phenId == specialFaultPhenId.toString()) {
                initProductCateg([]);

                // 显示特殊故障提示信息
                if (!checkEleShow("#specialFaultPhenTip")) {
                    let tipInfo = `<div class="layui-input-inline layui-inline-text"  style="color:red" id="specialFaultPhenTip"><span>特殊故障需使用 服务项目报价 ，如更换电视屏幕、控制板、压缩器、等故障，详见下图全部特殊故障；</span></div>`;
                    $("#faultPhen").append(tipInfo);
                }
            } else {
                fetchProductCateg(phenId, null, null);

                $("#specialFaultPhenTip").remove();
            }

            // 初始化价格表
            loadAdvanceQuotePriceTable();

            // 重新加载报价产品优惠信息
            reloadAdvanceQuoteDiscount();
        });
        form.on("radio(productCateg)", function (data) {
            var cityId = getters.getCityId();
            var channelId = getters.getChannelId();
            var showType = 1;
            var servCategId = newGetters.getServCategId(0);
            var bizType = getters.getBizType();
            var productId = newGetters.getProductId();
            var platWork = getters.getPlatWork();
            let brandId = getLayuiSelectValue("#brand0");
            if (!cityId || !channelId || !servCategId || !productId || !brandId) {
                return;
            }
            let categId = data.value;

            let itemId = newGetters.getItemId();
            let phenId = newGetters.getPhenId();
            // 二级分类获取产品
            let requestURL = "";
            let phenDisplay = $("#faultPhenDiv").css("display");
            if (phenDisplay != "none") {
                // 故障现象获取产品
                requestURL = LIST_PRODUCT_WITH_PHEN_URL;
            } else {
                // 服务项目获取产品
                requestURL = LIST_PRODUCT_WITH_ITEM_URL;
            }

            $.ajax({
                    url: requestURL,
                    type: "POST",
                    data: JSON.stringify({
                        bizType: bizType,
                        channelId: channelId,
                        platWork: platWork,
                        cityId: cityId,
                        showProductId: productId,
                        itemId: itemId,
                        categId: categId,
                        phenId: phenId,
                        brandId: brandId
                    }),
                    processData: false,
                    contentType: "application/json;charset=UTF-8",
                    error: function () {
                        alert('获取信息失败');
                    },
                    success: function (rsp) {
                        if (rsp.status === 200) {
                            // 请求成功
                            if (rsp.data) {
                                initQuoteProduct(rsp.data);
                            }
                        }
                    }
                }
            );

            // 初始化价格表
            loadAdvanceQuotePriceTable();

            // 重新加载报价产品优惠信息
            reloadAdvanceQuoteDiscount();

        });
        form.on("radio(quoteProduct)", function (data) {

            let productId = data.value;
            // 初始化价格表
            loadAdvanceQuotePriceTable(productId);

            // 重新加载报价产品优惠信息
            reloadAdvanceQuoteDiscount();

            // 重新设置价格信息
            if (checkEleShow('#productNameDiv')) {
                // 显示

                // 获取当前产品价格信息
                let $product = $('input[name="quoteProduct"]:checked');
                let price = $product.data("price");

                let productNum = newGetters.getCount(0);

                var str = price / 100 + "" + "元";
                $("#amount0").text(str).data("price", price);

                // 总价
                let totalStr = price * productNum / 100 + "" + "元";
                $("#totalAmount0").text(totalStr).data("price", price);
            }
        });
    }

    /**
     * 初始公司信息
     */
    function initCompanyInfo() {

        // 是否平台直派
        if (isGrid) {
            return;
        }

        var dataList = window.EventBus.list;
        var removeList = window.EventBus.removeList;
        var firstDataIndex = 0;
        dataList.forEach(function(item, index) {
            if (window.EventBus.checkRemove(index)) {
                firstDataIndex = index;
                return;
            }
        });

        var plat = getters.getPlatWork();
        var servCategId = newGetters.getServCategId(firstDataIndex);
        var channelId = getters.getChannelId();
        var cityId = getters.getCityId();
        var type = getters.getOrderType();
        var dutyTime = newGetters.getDutyTime(firstDataIndex);
        var workId = getters.getWorkId();

        var bizType = getters.getBizType();
        var productShowType = newGetters.getProductShowType(firstDataIndex);
        var productId = newGetters.getProductId(firstDataIndex);
        var longitude = getters.getLongitude();
        var latitude = getters.getLatitude();
        var streetSource = getters.getStreetSource();

        // 返修单修改，不初始化公司信息
        if (!options.isNew && getters.getOrderType() == ORDER_TYPE_ENUM.REWORK) {
            setCompanyInfo($("#hidCompany").val());
            return;
        }

        if (!plat ||
            !productId ||
            !longitude ||
            !latitude ||
            dataList.length - removeList.length > 1
        ) {
            setCompanyInfo("");
        } else {
            fetchCompanyName(
                plat,
                channelId,
                cityId,
                type,
                dutyTime,
                workId,
                bizType,
                servCategId,
                productShowType,
                productId,
                longitude,
                latitude,
                streetSource
            ).then(function(res) {
                if (!res) {
                    setCompanyInfo(
                        '<span style="color: red">当前平台无法服务</span>'
                    );
                    $('#confirmbtn').addClass("layui-btn-disabled").attr("disabled", true);
                } else if (res.data == 0 || res.data == 4) {
                    // 所有平台都无法服务
                    setCompanyInfo(
                        '<span style="color: #FF0000">' + res.message + "</span>"
                    );
                    $('#confirmbtn').addClass("layui-btn-disabled").attr("disabled", true);
                } else if (res.data == 1) {
                    // 单个服务
                    let message = res.message.split("-");
                    $("#preManageCompanyId").val(message[0]);
                    $("#preManageCompanyName").val(message[1]);
                    /*let msg = message[1] || "";
                    if (msg.indexOf('无法承接线索') != -1) {
                      setCompanyInfo(
                          '<span style="color: #FF0000">' + msg + "</span>"
                      );
                    } else {*/
                    setCompanyInfo(message[1] || "");
                    $('#confirmbtn').removeClass("layui-btn-disabled").attr("disabled", false);
                    //}
                } else if (res.data == 2) {
                    // 多个服务商
                    $("#preManageCompanyId").val(0);
                    setCompanyInfo(res.message || "");
                    $('#confirmbtn').removeClass("layui-btn-disabled").attr("disabled", false);
                } else {
                    setCompanyInfo(res.message || "");
                    $('#confirmbtn').removeClass("layui-btn-disabled").attr("disabled", false);
                }
            });
        }
    }

    /**
     * 描述: 图片上传方法
     * @param elemId
     * @param valueId
     */
    let indexUploadImags;

    function uploaderImage(elemId, valueId) {
        upload.render({
            elem: '#' + elemId,
            exts: 'jpg|png|jpeg',
            acceptMime: 'image/*',
            accept: 'images',
            url: '/work/modify/uploader/orderPhoto?timestamp=' + new Date().getTime() + '&elemId=' + elemId,
            size: 5120,
            beforeSend: function(obj) {
                indexUploadImags = layui.layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            },
            done: function(res) {
                if (res.status == 200) {
                    var data = res.data;
                    $("#" + valueId).val(data);
                    $("#" + valueId + "s").attr("src", data).attr("style", "width: 0;height: 0");
                    reLoadImage(elemId, data);
                } else {
                    layer.msg(res.message)
                }
                layui.layer.close(indexUploadImags);
            }
        });
    }

    function reLoadImage(elemId, value, valueId) {
        zmnUploadUtil.reLoadImage($, elemId, value, valueId);
        let next = $("#" + elemId + "Value").next();
        let next1 = $(next).next();
        $(next).attr("style", "visibility:hidden !important");
        $(next1).attr("style", "visibility:hidden !important");
    }

    /**
     * 初始化预约时间相关时间
     * @param {string} time 时间
     */
    function initDutyTimeInfo(showTime, time, index, isToday) {
        setTimeout(function() {
            $("#duty-time-input" + index).val(time);
            $("#duty-time" + index).text(showTime);
            if (isToday != undefined && !isToday) {
                $("#duty-time" + index).addClass('text-red');
            } else {
                $("#duty-time" + index).removeClass('text-red');
            }
        }, 1000);
    }

  /**
   * 选择预约时间相关时间-不延时
   * @param {string} time 时间
   */
  function selectDutyTimeInfo(showTime, time, index, isToday) {
    $("#duty-time-input" + index).val(time);
    $("#duty-time" + index).text(showTime);
    if (isToday != undefined && !isToday) {
      $("#duty-time" + index).addClass('text-red');
    } else {
      $("#duty-time" + index).removeClass('text-red');
    }
  }

  /**
   * 计算产品价格
   */
  function calculateProductAmount(index) {
    if (!index) {
      var index = 0;
    }
    // 录入手机单不展示价格表
    if (options.isEntrust === true) {
      return;
    }

        var type = $('input[name="type"]:checked').val();
        var servCategId = index ?
            getLayuiSelectValue("#servCategoryId" + index) :
            getLayuiSelectValue("#servCategoryId0");

        var count = newGetters.getCount(index);
        var cityId = getters.getCityId();
        var productId = newGetters.getProductId(index || 0);
        var channelId = getters.getChannelId();
        var bizType = getters.getBizType();
        if (
            (!type && !servCategId) ||
            !count ||
            !cityId ||
            !productId ||
            !channelId
        ) {
            $("#amount-wrapper" + index).hide();
            $("#discount-wrapper" + index).hide();
            $("#max-discount-div" + index).hide();
            $("#amount" + index).val("");
            return;
        }
      $("#discount-wrapper" + index).show();

      // 判断是否需要报价，如果需要，不显示
      if (checkEleShow("#quoteTypeDiv")) {
          return;
      }

        $("#amount-wrapper" + index).show();
        showToatlAmountDiv(
            type,
            servCategId,
            count,
            cityId,
            productId,
            channelId,
            bizType,
            index
        );
    }

    /**
     * 计算所有派单工程师
     */
    function calculateAllDistributeMaster() {
        const list = window.EventBus.list;
        list.forEach(function(el, index) {
            if (window.EventBus.checkRemove(index)) {
                calculateDistributeMaster(index);
            }
        });
    }

    function clearAllDistributeMaster() {
        const list = window.EventBus.list;
        list.forEach(function(el, index) {
            if (window.EventBus.checkRemove(index)) {
                $("#distributeMasterId" + index).val('');
                $("#distribute-master" + index).text('');
                $("#distributeMasterLog" + index).val('');
                $("#distributeJsonStr" + index).val('');
            }
        });
    }

    /**
     * 计算派单工程师
     * @param index
     */
    function calculateDistributeMaster(index) {
        console.log("计算派单工程师");
        // 没应用库存
        if (!options.isDistributeMaster) {
            return;
        }
        if (options.isDistributeMaster === false) {
            return;
        }

        setTimeout(function(index) {
            if (!index) {
                var index = 0;
            }
            var plat = getters.getPlatWork();
            var bizType = getters.getBizType();
            var servCategId = getLayuiSelectValue("#servCategoryId" + index);
            var productId = getLayuiSelectValue("#product" + index);
            var checkProductId = newGetters.getProductId(index);
            var showProductId = getLayuiSelectValue("#showProduct" + index);
            var productCount = newGetters.getCount(index);
            var dutyTime = newGetters.getDutyTime(index);
            var provinceId = getters.getProvinceId();
            var countyId = getters.getCountyId();
            var streetSource = getters.getStreetSource();
            var cityId = getters.getCityId();
            var streetId = getters.getStreetId() || $('#communityId').val();
            var latitude = getters.getLatitude();
            var longitude = getters.getLongitude();
            var channelId = getters.getChannelId();
            var telephone = getters.getTelephone();
            var telephone2 = getters.getTelephone2();
            var telephone3 = getters.getTelephone3();
            var test = getters.getTest();

            if (!bizType ||
                !servCategId ||
                !checkProductId ||
                !productCount ||
                !cityId ||
                !provinceId ||
                !countyId ||
                !streetSource ||
                !streetId ||
                !latitude ||
                !longitude ||
                !channelId ||
                !dutyTime ||
                !test) {
                $("#distributeMasterId" + index).val('');
                $("#distribute-master" + index).text('');
                $("#distributeMasterLog" + index).val('');
                $("#distributeJsonStr" + index).val('');
                return;
            }

            // 依赖 showToatlAmountDiv 方法
            var maxProductCount = $("#maxProductCount" + index).val();
            if (maxProductCount <= 1) {
                productCount = 1;
            }

            if (test == 2) {
                $("#distributeMasterId" + index).val('');
                $("#distribute-master" + index).text('');
                $("#distributeMasterLog" + index).val('');
                $("#distributeJsonStr" + index).val('');
                return;
            }

            if (!isGrid || !isSelectMaster) {
                $("#distributeMasterId" + index).val('');
                $("#distribute-master" + index).text('');
                $("#distributeMasterLog" + index).val('');
                $("#distributeJsonStr" + index).val('');
                return;
            }

            if (!isWhiteWorkCity) {
                $("#distributeMasterId" + index).val('');
                $("#distribute-master" + index).text('');
                $("#distributeMasterLog" + index).val('');
                $("#distributeJsonStr" + index).val('');
                return;
            }

            if (!isAutoDistributeTimeWithin) {
                $("#distributeMasterId" + index).val('');
                $("#distribute-master" + index).text('');
                $("#distributeMasterLog" + index).val('');
                $("#distributeJsonStr" + index).val('');
                return;
            }

            var params = {
                plat: plat,
                bizType: bizType,
                servCategId: servCategId,
                productId: productId,
                showProductId: showProductId,
                productNumber: productCount,
                dutyTime: dutyTime,
                provinceId: provinceId,
                countyId: countyId,
                streetSource: streetSource,
                cityId: cityId,
                streetId: streetId,
                latitude: latitude,
                longitude: longitude,
                channelId: channelId,
                telephone: telephone,
                telephone2: telephone2,
                telephone3: telephone3,
            };

            $http.lockSave(GET_PRE_DISTRIBUTE_MASTER_URL, params).then(
                function(data) {
                    $("#distribute-master" + index).text(data.distributeMasterLog);
                    $("#distributeMasterLog" + index).val(data.distributeMasterLog);
                    if (data.existMater) {
                        $("#distributeMasterId" + index).val(data.distributeMasterId);
                        $("#distributeJsonStr" + index).val(data.distributeJsonStr);
                        if (data.changeDutyTime) {
                            initDutyTimeInfo(data.showDutyTime, data.dutyTime, index, data.isToday);
                            initCompanyInfo();
                        }
                    } else {
                        $("#distributeMasterId" + index).val('');
                        $("#distributeJsonStr" + index).val('');
                    }
                },
                function(msg) {
                    layer.msg(msg);
                }
            );

    }, 2000, index);
  }
  var formUtils = {
    normalizeDutyTime: function (dateStr) {
      return util.toDateString(new Date(dateStr));
      // return dayjs(dateStr).format('YYYY-MM-DD HH:mm:ss');
    },
    normalizeFaults: function (data, index) {
      var str = "faultIdList" + index;
      var faultArray = data
          .filter((item) => {
            return item.name === str;
          })
          .reduce((acc, curr) => {
            acc.push(curr.value);
            return acc;
          }, []);
      return faultArray;
    },
    _emptyValueFilter: function (data) {
      var params = {};

            Object.keys(data).forEach((key) => {
                if (data[key] == null || data[key] === "") {
                    return;
                }
                params[key] = data[key];
            });

            return params;
        },
        normalize: function(data) {
            var params = {};
            var excludeArr = [
                "faultIdList",
                "productId",
                "brandId",
                "number",
                "faultRemark",
                "commonRemark",
            ];

            var field = data.field;
            var formData = $(data.form).serializeArray();

            // 如果streetid为null 就把queryCommunity 接口里的 communityId 赋值给 streetId
            if (!field.streetId) {
                field.streetId = $('#communityId').val();
            }

            Object.keys(field).forEach((key) => {
                if (excludeArr.indexOf(key) === -1) {
                    params[key] = field[key];
                }
            });

            if (!field.brandId) {
                field.brandId = $('#brand option:contains("其他")').val();
            }

            if (field.nextContactDate) {
                params.nextContactTime =
                    field.nextContactDate + " " + field.nextContactTime;
            }
            const newOrderProductList = [];
            const distributeMasterList = [];
            const list = window.EventBus.list;
            var ischeck = true;
            list.forEach(function(el, index) {
                if (window.EventBus.checkRemove(index)) {
                    if (!checkDutyTime(index)) {
                        layer.alert("请选择每一个产品的预约时间");
                        ischeck = false;
                        return;
                    }
                    allnumber = allnumber + Number(field["number" + index]);
                    let orderProduct = {
                        servCategId: field["servCategId" + index],
                        brandId: field["brandId" + index] || 0,
                        productId: field["productId" + index] || 0,
                        showProductId: field["showProductId" + index] || 0,
                        productShowType: field["productShowType" + index] || 0,
                        number: field["number" + index],
                        remark: field["faultRemark" + index],
                        faultIdList: formUtils.normalizeFaults(formData, index),
                        dutyTime: field["dutyTime" + index],
                        servItemType: field["servItemType" + index],
                        sendDiscountFlag: field["sendDiscountFlag" + index],
                    };

                    // 处理优惠券 如果需要发放并且有的话
                    let discountMap = new Map();
                    let realTelephone = getters.getTelephone();
                    if (discountTelephoneMap.get(realTelephone) && discountTelephoneMap.get(realTelephone).get(index)) {
                        discountMap = discountTelephoneMap.get(realTelephone).get(index);
                    }
                    // 最佳优惠 如果勾选了，一起发放
                    if (orderProduct.sendDiscountFlag === 'on' && bestDiscountTelephoneMap.get(realTelephone) && bestDiscountTelephoneMap.get(realTelephone).get(index)) {
                        let bestDiscountMap = bestDiscountTelephoneMap.get(realTelephone).get(index);
                        for (let key of bestDiscountMap.keys()) {
                            discountMap.set(key, bestDiscountMap.get(key));
                        }
                    }

                    orderProduct.waitSendDiscountList = Array.from(discountMap.values());

                    // 处理提前报价逻辑
                    if (index == 0 && checkEleShow("#quoteTypeDiv")) {
                        let result = checkQuoteInfo(field);
                        if (result) {
                            layer.alert(result);
                            ischeck = false;
                            return;
                        }
                        let itemId = $('input[name="quoteProduct"]:checked').data("item-id");
                        let phenId = newGetters.getPhenId();
                        let phenName = newGetters.getPhenName();
                        let advanceQuote = {
                            quoteType: field.quoteType,
                            phenId: phenId,
                            phenName: phenName,
                            itemId: itemId,
                            productCateg: field.productCategId
                        };
                        orderProduct.advanceQuote = advanceQuote;
                        orderProduct.productId = field.quoteProduct;
                        orderProduct.productShowType = 1;
                    }

                    newOrderProductList.push(orderProduct);

                    distributeMasterList.push({
                        showProductId: field["showProductId" + index] || 0,
                        productId: field["productId" + index] || 0,
                        distributeMasterId: field["distributeMasterId" + index],
                        distributeMasterLog: field["distributeMasterLog" + index],
                        distributeJsonStr: field["distributeJsonStr" + index],
                    });
                }
            });
            params.newOrderProductList = newOrderProductList;
            params.distributeMasterList = distributeMasterList;

            // 常见备注
            params.commonRemarkList = getters.getCommonRemarkList();
            // 外部店铺信息
            params.externalShopInfo = getters.getExternalShopInfo();

            return ischeck ? this._emptyValueFilter(params) : "";
        },
    };

    /**
     * 判断是否是计价器类型的工单，如果是，显示amount-fault如果不是，显示amount-others
     */
    function showToatlAmountDiv(
        type,
        servCategId,
        count,
        cityId,
        productId,
        channelId,
        bizType,
        index
    ) {
        var plat = getters.getPlatWork();
        var type = getters.getOrderType();
        var params = {
            cityId: cityId,
            productId: productId,
            channelId: channelId,
            bizType: bizType,
            plat: plat,
            productShowType: newGetters.getProductShowType(index),
            brandId: newGetters.getBrandId(index),
            type: type,
        };

    // 目前只支持啄木鸟
    $http
        .$get(GET_SERVITEM_TYPE_INFO_WORK_URL, params)
        .done(function (data) {
          // 计价器类型工单
          $("#servItemType" + index).val(data.servItemType);
          if (type == "2") {
            $("#amount-others" + index).hide();
            $("#amount-quotation" + index).hide();
            $("#amount-advance-pay" + index).hide();
            $("#amount-quotation-three" + index).hide();
          } else {
            if (data.servItemType == "1") {
              $("#amount-others" + index).show();
              $("#amount-quotation" + index).hide();
              $("#amount-advance-pay" + index).hide();
              $("#amount-quotation-three" + index).hide();
            } else if (data.servItemType == "2") {
              $("#amount-others" + index).hide();
              $("#amount-advance-pay" + index).hide();
              $("#amount-quotation-three" + index).hide();
              $("#amount-quotation" + index).show();
            } else if (data.servItemType == "3") {
              $("#amount-others" + index).hide();
              $("#amount-advance-pay" + index).show();
              $("#amount-quotation-three" + index).hide();
              $("#amount-quotation" + index).hide();
            } else if (data.servItemType == "4" || data.servItemType == "5") {
              $("#amount-others" + index).hide();
              $("#amount-advance-pay" + index).hide();
              $("#amount-quotation" + index).hide();
              $("#amount-quotation-three" + index).show();
              var str = '';
              if (data.servItemType == "4") {
                str = '计价器3.0';
              }else if (data.servItemType == "5") {
                str = '一口价';
              }

              if (zmnUtils.isNumber(data.price)) {
                str += '订单，收费为' + data.price / 100 + '元起，具体费用工程师上门检测后确定';
              }else {
                str += '订单，具体费用工程师上门检测后确定';
              }
              $('#amount-quotation-three-text' + index).text(str);
            }
          }

                // 清空金额缓存
                $("#amount" + index).data("price", 0);
                $("#totalAmount" + index).data("price", 0);

          // 产品数量
            let productNum = newGetters.getCount(index);

                if (data.isShow === 1) {
                    $("#amount-detail" + index).hide();
                } else if (zmnUtils.isNumber(data.price) && data.unit) {
                    $("#amount-detail" + index).show();
                    var str = data.price / 100 + "" + "元/" + data.unit;
                    $("#amount" + index).text(str).data("price", data.price);

                    // 总价
                    let totalStr = data.price * productNum / 100 + "" + "元";
                    $("#totalAmount" + index).text(totalStr).data("price", data.price);
                } else if (zmnUtils.isNumber(data.price)) {
                    $("#amount-detail" + index).show();
                    var str = data.price / 100 + "" + "元";
                    $("#amount" + index).text(str).data("price", data.price);

                    // 总价
                    let totalStr = data.price * productNum / 100 + "" + "元";
                    $("#totalAmount" + index).text(totalStr).data("price", data.price);
                } else {
                    $("#amount-detail" + index).hide();
                }

                var isShow = data.isShow !== 1;
                reloadDiscountInfo(data.price, index, isShow);

                // 新单，非计价器产品，有多个后台产品时数量必须为1，其它可大于1
                if (type == "1" && data.isShow === 2 && !isQuotation(data.servItemType)) {
                    maxProductCount = 10;
                    $("#maxProductCount" + index).val(10);
                } else {
                    maxProductCount = 1;
                    $("#maxProductCount" + index).val(1);
                }
            })
            .fail(function(msg) {
                layer.msg(msg);
            });
    }

    /**
     * 省份选择下拉框选中事件处理函数
     * @param provinceId 省份 id
     */
    function handleProvinceSelect(provinceId) {
        // 更新下拉框选项状态
        updateOptionsStatus($("#provinceId"));

        // 渲染城市下拉框
        initCitySelect(provinceId, getters.getChannelId(), false);

        // 清空区域列表
        renderServiceArea([]);

        // 清空街道信息
        renderStreetIdSelect([]);

        // 清空地址
        clearAddress();

        // 计算价格

        // calculateProductAmount();
        var list = window.EventBus.list;
        list.forEach(function(item, index) {
            if (window.EventBus.checkRemove(index)) {
                calculateProductAmount(index);
            }
        });

        try {
            // 初始化公司信息
            if (this.list.length == this.removeList + 1) {
                initCompanyInfo();
            }
        } catch (e) {}

    // 计算派单工程师
    // calculateAllDistributeMaster();
  }

    /**
     * 城市选择下拉框选中事件处理函数
     */
    function handleCitySelect(cityId) {
        var $city = $("#cityId");

        // 更新下拉框选项状态
        updateOptionsStatus($city);

        // 初始化服务区域
        initServiceArea(cityId);
        // 清空地址
        clearAddress();

        // 清空街道信息
        renderStreetIdSelect([]);

        // 初始化预约时间
        /*initDutyTime(0,function () {
          // 初始化服务公司信息
          initCompanyInfo();
        });*/
    }

    /**
     * 城市选择下拉框选中事件处理函数
     */
    function handleCountySelect(countyId, cb) {
        if (countyId) {
            fetchAreaDetailData(countyId).done(function(data) {
                renderStreetIdSelect(data, cb);
            });
        }
    }

    function verifyStreetValidation(params) {
        params.type = getters.getOrderType();
        params.add = options.isNew ? 2 : 1;
        return $http.get(STREET_VALIDATION_URL, params).then(function(data) {
            if (data.status !== 2) {
                return $.Deferred().reject("所选地址不在服务范围");
            }
            var $city = $('#cityId option[value="' + data.cityId + '"]:selected');

            if (!$city[0]) {
                return $.Deferred().reject("所选地址与所选城市不匹配");
            }

            return data;
        });
    }

    /**
     *  标准需要查询的城市名称
     * @param cityName 城市名称
     * @returns {String}
     */
    function normalizeCityName(cityName) {
        return cityName.replace("辖县", "").replace("辖区", "");
    }

    /**
     * 获取城市名称
     * @returns {String} 城市名称
     */
    function getSelectedCityName() {
        return normalizeCityName($("#cityId option:selected").text());
    }
    /**
     * 分点城市切换主城市
     * @returns {String} 城市名称
     */

    function switchCity(cityId) {
        var $cityId = $("#cityId");
        $cityId.val(cityId);
        form.render("select");

        updateOptionsStatus($cityId);
    }

    /**
     * 更新 区域列表
     * @param countyId 区域 Id
     */
    function updateAreaList(countyId) {
        var $areaItems = $("#county-list span");
        $areaItems.removeClass("current");
        if (!countyId) {
            return;
        }

        $areaItems.filter('[data-id="' + countyId + '"]').addClass("current");
    }

    /**
     * 更新区域输入框的值
     * @param countyId 区域 Id
     */
    function updateAreaInput(countyId) {
        $("#countyId").val(countyId);
    }

    /**
     * 更新区域相关信息
     * @param countyId 区域 Id
     */
    function updateAreaInfo(countyId) {
        updateAreaList(countyId);
        updateAreaInput(countyId);
    }

    /**
     * 更新服务坐标信息
     * @param lnt 经度
     * @param lat 纬度
     */
    function setStreetSource(value) {
        $('#streetSource').val(value);
    }

    function setStreetId(value) {
        $('#communityId').val(value);
    }

    function updateLocationInfo(lnt, lat) {
        $("#longitude").val(lnt);
        $("#latitude").val(lat);
    }

    /**
     * 更新街道信息
     * @param {string} value 街道信息
     */
    function updateStreetInfo(value) {
        $("#customerAddress").val(value);
    }

    /**
     * 更新街道信息
     * @param {string} value 街道信息
     */
    function updateDistrict(value) {
        $("#district").val(value);
    }

    function manualSetFormValue(values) {
        form.val("zmn-order-add-form", values);
    }

    function manualSetSelectValue(selector, value) {
        var $select = $(selector);
        $select
            .find("option")
            .removeProp("selected")
            .prop("disabled", false)
            .prop("selected", false);
        $select
            .find('option[value="' + value + '"]')
            .prop("selected", true)
            .prop("disabled", true);
    }

    /**
     * 检查服务是否可用
     */
    function checkServiceValidation(index) {
        var lng = $("#longitude").val();
        var lat = $("#latitude").val();

        var channelId = getters.getChannelId();
        var cityId = $("#cityId option:selected").val();
        var servCategId = getters.getServCategId();
        var productShowType = getters.getProductShowType();
        var productId = getters.getProductId();
        var countyId = getters.getCountyId();

        if (!channelId) {
            layer.msg("请先选择渠道");
            return;
        } else if (!cityId) {
            layer.msg("请先选择城市");
            return;
        } else if (!servCategId) {
            layer.msg("请先选择服务类型");
            return;
        } else if (!productId) {
            layer.msg("请先选择产品");
            return;
        }

        // 验证所选地址是否在服务范围
        verifyStreetValidation({
            bizType: getters.getBizType(),
            productId: productId,
            channelId: channelId,
            cityId: cityId,
            longitude: lng,
            latitude: lat,
            servCategId: servCategId,
            productShowType: productShowType,
            countyId: countyId
        }).then(
            function(data) {
                if (cityId != data.cityId) {
                    switchCity(data.cityId);
                }

                updateAreaInfo(data.countyId);
                updateLocationInfo(lng, lat);

          // 初始化公司信息
          var list = window.EventBus.list;
          var removeList = window.EventBus.removeList;
          list.forEach(function (item, index) {
            if (
                window.EventBus.checkRemove(index) &&
                list.length == removeList.length + 1
            ) {
              initCompanyInfo();
              // 初始化行政服务商
              initGridCompany();
            }
          });
        },
        function (msg) {
          layer.msg(msg);
          clearAddress();
          updateAreaInfo("");
        }
    );
    // 计算派单工程师
    // calculateAllDistributeMaster();
  }

    /**
     * 检查服务信息完成性
     */
    function checkServiceInfoCompleteness(index) {
        var lng = $("#longitude").val();
        var lat = $("#latitude").val();
        var customerAddress = $("#customerAddress").val();

        var channelId = getters.getChannelId();
        var cityId = $("#cityId option:selected").val();
        var servCategId = getters.getServCategId();
        var productId = getters.getProductId();
        return (
            lng &&
            lat &&
            customerAddress &&
            channelId &&
            cityId &&
            servCategId &&
            productId
        );
    }

    /**
     * 检查百度地图插件是否可用
     * @returns {{msg: string, status: boolean}}
     */
    function checkMapAvailability() {
        var result = {
            status: true,
            msg: "",
        };

        var channelId = getters.getChannelId();
        var cityId = $("#cityId option:selected").val();
        var productId = getters.getProductId();

        if (!channelId) {
            result = {
                status: false,
                msg: "请先选择渠道",
            };
        } else if (!cityId) {
            result = {
                status: false,
                msg: "请先选择城市",
            };
        }

        return result;
    }

    // 检查城市
    function checkChannelIdAndCityId(channelId, cityId) {
        if (!channelId || !cityId) return;

        var params = {
            channelId: channelId,
            cityId: cityId,
            showType: getters.getProductShowType(),
        };

        $http.get(CHECK_CHANNELID_CITYID_URL, params).then(
            function(data) {},
            function(msg) {
                zmnUtils.layui.toastError(msg);
                initCitySelect(getters.getProvinceId(), channelId, false);
                if (msg.indexOf("未开通") > 0) {
                    clearAddress();
                }
            }
        );
    }

    /**
     * 检查是否平台直派
     * @param plat
     * @param cityId
     * @param bizType
     */
    function checkGrid(cityId) {
        // 返修单不显示校验服务商
        if (!options.isNew && getters.getOrderType() == ORDER_TYPE_ENUM.REWORK) {
            return;
        }
        $http
            .$get(IS_GRID, {
                platWork: getters.getPlatWork(),
                cityId: cityId,
                bizType: getters.getBizType(),
            })
            .then(
                function(data) {
                    if (data == 20) {
                        $("#preCompany").text("校验服务商");
                        isGrid = false;
                        $("#gridCompany").html("");
                    } else {
                        $("#preCompany").text("");
                        isGrid = true;
                        $("#company").html("");
                    }
                },
                function(msg) {
                    layer.msg("网络错误");
                }
            );
    }

    /**
     * 获取自动派单时间
     * @param plat
     * @param cityId
     * @param bizType
     */
    function getAutoDistributeTime(index) {
        if (!getters.getCityId()) {
            $("#auto-distribute-time" + index).text('');
            return;
        }
        $http
            .$get(GET_AUTO_DISTRIBUTE_TIME, {
                platWork: getters.getPlatWork(),
                cityId: getters.getCityId(),
                bizType: getters.getBizType(),
            })
            .then(
                function(data) {
                    if (data) {
                        $("#auto-distribute-time" + index).text('当前城市的自动派单时间：' + data);
                        let timeArray = data.split("-");
                        let autoTimeStart = timeArray[0].replace(":", "");
                        let autoTimeEnd = timeArray[1].replace(":", "");
                        let newTime = new Date().format("hh:mm").toString().replace(':', '');
                        if (newTime >= autoTimeStart && newTime <= autoTimeEnd) {
                            isAutoDistributeTimeWithin = true;
                        } else {
                            isAutoDistributeTimeWithin = false;
                        }
                    } else {
                        $("#auto-distribute-time" + index).text('');
                    }
                },
                function(msg) {}
            );
    }

  /**
   * 判断是否是正整数且最多小数点后两位;
   * @param val {number/string} 字符串或数字
   * @returns {boolean} 返回是否是数字
   */
  function isNumber(val) {
    var reg = /^[0-9]+([.]{1}[0-9]{1,2})?$/;//正整数到小数点后两位
    return reg.test(val);
  }

    /**
     * 初始化页面事件
     */
    function initEvent() {
        $('body').on('paste', '#telephone, #telephone2, #telephone3', function(e) {
            if (this.disabled) {
                return;
            }
            // 粘贴处理
            let $telephone = $(this);
            let pastedData = e.originalEvent.clipboardData.getData('text');
            if (pastedData && pastedData.match(/\{\s*\"show\"\s*\:\s*\"(?<show>.+)\"\s*\,\s*\"ciphertext\"\s*\:\s*\"(?<ciphertext>.+)\"\s*\}/)) {
                let data = JSON.parse(pastedData);
                $telephone.val(data.show);
                $telephone.data('val', data.show);
                $telephone.data('crypto-phone', data.ciphertext);
                // 解密处理
                $http.get(GET_DECRYPT_PHONE_URL, {
                    cryptoPhone: data.ciphertext
                }).then(
                    function(data) {
                        $telephone.data('real-val', data.realPhone);
                        $telephone.trigger('change');
                    },
                    function(msg) {
                        $telephone.val('');
                        $telephone.data('val', '');
                        $telephone.data('real-val', '');
                        $telephone.data('crypto-phone', '');
                        $telephone.trigger('change');
                    }
                );
            } else {
                $telephone.val(pastedData.replace(/\s+/g,""));
                $telephone.data('val', '');
                $telephone.data('real-val', '');
                $telephone.data('crypto-phone', '');
                $telephone.trigger('change');
            }

            return false;
        });


        // 电话号码输入框输入事件
        $("#telephone, #telephone2, #telephone3").on("input", function() {
            var $this = $(this);
            $this.val($this.val().replace(/[^\d]/gi, ""));

              // 计算库存
              var telephone = $this.val();
              if (telephone == '') {
                return;
              }
              // if (validate.phone(telephone)) {
              //   // 计算库存
              //   calculateAllDistributeMaster();
              //   return;
              // }
        });

        // 电话号码变更时间
        $("#telephone, #telephone2, #telephone3").on("change", function() {
            checkAllDuplicateOrder();
        });

        //自定义验证规则
        form.verify({
            radio: function(value, item) {
                var $ = layui.$;
                var verifyName = $(item).attr("name"),
                    verifyType = $(item).attr("type"),
                    formElem = $(item).parents(".layui-form"), //获取当前所在的form元素，如果存在的话
                    verifyElem = formElem.find("input[name=" + verifyName + "]"), //获取需要校验的元素
                    isTrue = verifyElem.is(":checked"), //是否命中校验
                    focusElem = verifyElem.next().find("i.layui-icon"); //焦点元素
                if (!isTrue || !value) {
                    //定位焦点
                    focusElem.css(
                        verifyType == "radio" ? { color: "#ff5722" } : { "border-color": "#ff5722" }
                    );
                    //对非输入框设置焦点
                    focusElem
                        .first()
                        .attr("tabIndex", "1")
                        .css("outline", "0")
                        .blur(function() {
                            focusElem.css(
                                verifyType == "radio" ? { color: "" } : { "border-color": "" }
                            );
                        })
                        .focus();
                    return "必填项不能为空";
                }
            },
            brand: function(value, item) {
                // 品牌验证， 家电安装、家电清洗、家电维修 必选，其它不必须
                var servCategId = getters.getServCategId();
                if (
                    (servCategId == "1001" ||
                        servCategId == "1002" ||
                        servCategId == "1003") &&
                    !value
                ) {
                    return "必填项不能为空";
                }
            },
          "channel-amount": function (val) {
            if (val) {
              if (!isNumber(val)) {
                return "请输入正整数且最多保留两位小数"
              }
                if(val > 10000000){
                    return "不能大于一千万"
                }
            }
          }
        });

        // 订单类型单选框的选中事件处理器
        form.on("radio(product-showtype)", function (data) {
            var value = data.value;

            const index = $(data.elem).attr("gotype");
            // 初始化服务分类
            renderServCategorySelect(function () {
                // 初始化产品下拉框
                initProduct("", "", index, value);
                // // 初始化产品数量输入框
                initCountInput(1, index);
                initProductUnit("", index);
                // // 初始化品牌下拉框
                initBrandSelect("", index);
                // // 初始化常见故障
                initCommonFaultsCheckboxGroup("", index);
                // 清理该产品的预约信息
                clearDutyTime(index);
                var str = "servCategoryA" + index;
                form.render("select", str);
            }, index);


            // 如果前面的信息完整就检查服务服务可用性
            if (checkServiceInfoCompleteness(index)) {
                checkServiceValidation(index);
            }

            // 初始化公司信息
            initCompanyInfo();
            // 计算派单工程师
            // calculateDistributeMaster(index);

            var str = "servCategoryA" + index;
            form.render("select", str);
        });

    //
    // form.on("radio(test-change)", function (data) {
    //   // 清空预派工程师
    //   if (data.value == 2) {
    //     clearAllDistributeMaster();
    //     return;
    //   }
    //   calculateAllDistributeMaster();
    // });

        // 省份选择下拉框的点击事件处理器
        form.on("select(province)", function(data) {
            handleProvinceSelect(data.value);
        });

        // 品牌下拉框
        form.on("select(brand)", function(data) {
            var list = window.EventBus.list;
            list.forEach(function(item, index) {
                if (window.EventBus.checkRemove(index)) {
                    calculateProductAmount(index);
                }
            });

            // 处理提前付逻辑
            setTimeout(function (){
                checkAdvanceQuote()
            }, 500);
        });

        // 城市选择下拉框的点击事件处理器
        form.on("select(city)", function (data) {
            var cityId = data.value;
            var provinceId = $(data.elem)
                .find('option[value="' + cityId + '"]')
                .data("pid");
            if (provinceId) {
                $("#provinceId").val(provinceId);
                form.render("select");
            }

            // 清空预发券相关信息，避免数据错误
            clearAllProductDiscountInfo(null, cityId, null);

            // 检查城市是否开通库存试点
            $http.get(objOfURL.checkCityIsWhiteCity, {cityId: cityId}).then(
                function (data) {
                    isWhiteWorkCity = data;
                },
                function (msg) {
                    zmnUtils.layui.toastError(msg);
                }
            );
            //是否平台直派
            checkGrid(cityId);

            var list = window.EventBus.list;
            list.forEach(function (item, index) {
                if (window.EventBus.checkRemove(index)) {

                    // 设置自动派单时间
                    // getAutoDistributeTime(index);

                    renderServCategorySelect(function () {
                        // 更新产品信息
                        initProduct("", "", index);

                        calculateProductAmount(index);

                        // 初始化预约时间
                        initDutyTime(index, function () {
                            // 初始化服务公司信息
                            initCompanyInfo();
                        });
                        // 计算派单工程师
                        // calculateDistributeMaster()
                    }, index);
                }
            });

            handleCitySelect(cityId);

            // 处理提前付逻辑
            checkAdvanceQuote();
        });

        // 区县选择下拉框的点击事件处理器
        form.on("select(countyId)", function(data) {
            var countyId = data.value;
            handleCountySelect(countyId);
        });

        // 街道选择下拉框的点击事件处理器
        form.on("select(streetId)", function(data) {
            recreatFuzzyInfo();

      var list = window.EventBus.list;
      list.forEach(function (item, index) {
        if (window.EventBus.checkRemove(index)) {
          // 初始化预约时间
          initDutyTime(index, function () {
            // 初始化服务公司信息
            initCompanyInfo();
          });
          // 初始化行政服务商
          initGridCompany();
          // 计算派单工程师
          // calculateDistributeMaster(index);
        }
      });

            // 初始化预约时间
            /*initDutyTime(0,function () {
              // 初始化服务公司信息
              initCompanyInfo();
            });*/
        });

        // 精确地址与模糊地址切换
        $("#address-type-exact").on("click", function(e) {
            initFuzzyAddress();
        });

        $("#address-type-fuzzy").on("click", function(e) {
            initExactAddress();
        });

        // 街道输入框输入事件
        (function initStreeInputEvent() {
            var timer = null;
            $("#customerAddress").on("input", function(e) {
                e.preventDefault();
                var $this = $(this);

                clearTimeout(timer);
                timer = setTimeout(function() {
                    var queryStr = $this.val();
                    var cityName = getSelectedCityName();
                    var cityId = getters.getCityId();
                    renderStreetSelect({
                        queryStr: queryStr,
                        cityName: cityName,
                        cityId: cityId,
                        ak: addOrderWebAk
                    });
                }, 300);
            });
        })();

        // 街道输入框获取焦点事件
        $("#customerAddress").on("focus", function(e) {
            var $this = $(this);

            var result = checkMapAvailability();
            if (!result.status) {
                layer.msg(result.msg);
                $this.blur();
            }
        });

    // 街道输入框失去焦点事件
    $("#customerAddress").on("blur", function (e) {
      setTimeout(function () {
        if($("#suggestPanel").is(':hidden')){
          initCompanyInfo();
          initGridCompany();
          // 计算派单工程师
          // calculateAllDistributeMaster();
        }
      }, 300);
    });

        $("#suggestPanel").on("click", "li:not(.tip)", function() {
            var $li = $(this);

            // 关闭遮罩层
            layer.closeAll();

            var lng = $li.data("lng");
            var lat = $li.data("lat");
            var name = $li.data("name");
            var district = $li.data("district");
            var streetSource = $li.data('source');
            var streetId = $li.data('communityid');

            updateLocationInfo(lng, lat);
            updateStreetInfo(name);
            updateDistrict(district);
            setStreetSource(streetSource);
            setStreetId(streetId);

            // 更新区域list
            setCountyInfo(district, lng, lat, function() {
                // 如果前面的信息完整就检查服务服务可用性
                if (checkServiceInfoCompleteness(0)) {
                    checkServiceValidation(0);
                }
            });

      // 初始化行政服务商
      initGridCompany();
      // 初始化全部预约时间
      initAllDutyTime();

            $("#suggestPanel").hide();
        });

        // 百度地图按钮点击事件
        $("#btn-map").on("click", function(e) {
            e.preventDefault();

            var result = checkMapAvailability();

            if (!result.status) {
                layer.msg(result.msg);
                return;
            }
            // 处理逻辑
            var cityId = getters.getCityId();
            var servCategId = getters.getServCategId();
            var productShowType = getters.getProductShowType();
            var productId = getters.getProductId();
            var bizType = getters.getBizType();

      parent.addressOptions = {
        location: getters.getLocation(),
        cityId: cityId,
        servCategId: servCategId,
        productShowType: productShowType,
        productId: productId,
        cityName: getters.getCityName(),
        street: getters.getStreet(),
        streetId: getters.getStreetId(),
        streetSource: getters.getStreetSource(),
        countyId: getters.getCountyId(),
        countyName : getters.getInputCountyName(),
        plat: getters.getPlatWork(),
        verifyFunc: function (selectedAddress, succ_cb, fail_cb) {
          setCountyInfo(selectedAddress.addressComponents.district, selectedAddress.point.lng, selectedAddress.point.lat, function (countyId) {
            verifyStreetValidation({
              bizType: bizType,
              cityId: cityId,
              servCategId: servCategId,
              productShowType: productShowType,
              productId: productId,
              longitude: selectedAddress.point.lng,
              latitude: selectedAddress.point.lat,
              countyId: countyId,
            }).then(
                function (data) {
                  if (cityId != data.cityId) {
                    switchCity(data.cityId);
                  }
                  succ_cb(data);
                },
                function (msg) {
                  fail_cb(msg);
                }
            );
          })
        },
        callBack: function (data, addressObj) {
          updateAreaInfo(data.countyId);
          updateStreetInfo(addressObj.address);
          updateLocationInfo(addressObj.point.lng, addressObj.point.lat);
          setStreetId(addressObj.communityId);
          setStreetSource(addressObj.streetSource);
          // 初始化公司信息
          initCompanyInfo();
          initGridCompany();
          // 初始化全部预约时间
          initAllDutyTime();
          // 计算派单工程师
          // calculateAllDistributeMaster();
        },
      };

            parent.layer.open({
                title: "选择地址",
                type: 2,
                area: ["90%", "90vh"],
                fix: true, //不固定
                maxmin: false,
                content: OMS_BASE_URL + "/order/addressmap.ation",
                end: function() {
                    $("#customerAddress").focus();
                },
            });
        });

        // 产品相关输入框的 focus 事件
        $("#product-list").on("focus", "input", function() {
            if (!$("#cityId option:checked").val()) {
                layer.msg("请先选择城市");
                $(this).blur();
            }
        });

        // 预约时间多选框勾选事件
        form.on("checkbox(duty-time-checkbox)", function(data) {
            dutyStatusCheck(data.elem.checked);
        });

        // 监听意向单添加按钮事件
        form.on("submit(purpose)", function(data) {
            savePurpose(data.field, data.elem).then(function() {
                layer.closeAll();

                zmnUtils.layui.toastSuccess("操作成功", function() {
                    location.reload();
                });
            });

            return false;
        });

        // 保存确认按钮点击事件
        form.on("submit(confirmbtn)", function(data) {
            allnumber = 0;
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(function() {
                // 保存
                var params = formUtils.normalize(data);

                // 提交之前的校验 无论工单类型
                if (!verifyBeforeSubmit(params.newOrderProductList)) {
                    return false;
                }

                if (params == "") {
                    return;
                }
                if (allnumber > 20) {
                    layer.alert("产品数目总数不可以大于20个", { offset: "250px" });
                    return;
                }
                // 复制工单，需要将platWork->plat
                if (params.isCopy) {
                    params.plat = getters.getPlatWork();
                }
                if (orderPostTable && table.cache["orderPostTable"]) {
                    params.orderPostList = table.cache["orderPostTable"];
                }
                params.countyName = reqCountyName;
                if (params.telephone && params.telephone.indexOf('*') > 0) {
                    params.telephone = $('#telephone').data('real-val');
                    delete params.realTelephone;
                }
                if (params.telephone2 && params.telephone2.indexOf('*') > 0) {
                    params.telephone2 = $('#telephone2').data('real-val');
                    delete params.realTelephone2;
                }
                if (params.telephone3 && params.telephone3.indexOf('*') > 0) {
                    params.telephone3 = $('#telephone3').data('real-val');
                    delete params.realTelephone3;
                }

                if (params.channelPrepayRadio == 2) {
                    if (!params.channelPrepayAmount || params.channelPrepayAmount.trim().length == 0) {
                        layer.msg("请填写实收金额");
                        return;
                    }
                    if (!params.channelPrepayCertificateSrc) {
                        layer.msg("请上传预付款凭证");
                        return;
                    }
                    params.channelPrepayAmount = accMul(params.channelPrepayAmount, 100);

                  var prepayAmountDetailItemList = [];
                  $('.prepay-amount-item').each(function () {
                    let $this = $(this);
                    let itemAmount = $this.val();
                    if (itemAmount && itemAmount.trim().length > 0) {
                      prepayAmountDetailItemList.push({
                        text: $this.parent().prev().text(),
                        value: accMul(itemAmount, 100)
                      });
                      params.channelPrepayAmount = accAdd(params.channelPrepayAmount, accMul(itemAmount, 100));
                    }
                  });
                  params.channelPrepayAmountDetailList = prepayAmountDetailItemList;
                }

                // 下单流程
               // checkRealPhoneAndSaveOrder(true, params, data);

                if (getters.isCheckRealPhone()) {
                    // 获取真实号码后才可以提交
                    initRealPhone(function (realPhone) {
                        params.telephone = realPhone;
                        // 检查重复
                        checkAllDuplicateOrder(function (duplicateProductList) {
                            if (duplicateProductList.length > 0) {
                                // 提示
                                let tipPre = "此用户有疑似相同的订单（";
                                let tipSuffix = "）正在服务，确定是否重复录入？";
                                let content = tipPre + duplicateProductList.join('，') + tipSuffix;
                                layer.confirm(content,
                                    {
                                        btn:['取消','确定'],
                                        skin:"tip-class",
                                        title:"提示"
                                    },
                                    function (index) {
                                        layer.close(index);
                                    }, function (index) {
                                        layer.close(index);
                                        beforeSaveOrder(params, data);
                                    })
                            } else {
                                beforeSaveOrder(params, data);
                            }

                        });
                    });
                    return;
                }

                beforeSaveOrder(params, data);

                // 检查真实手机号
                // checkRealPhoneAndSaveOrder(true, params, data);

                /*saveOrderInfo(params, data.elem).then(
                    function (data) {
                      layer.msg("操作成功", { icon: 1, time: 1000 }, function () {
                        zmnUtils.isFunction(options.success)
                            ? options.success(data)
                            : options.modifyDetail
                            ? goWorkModifyDetail(
                                data.orderWork.orderId,
                                data.orderWork.workId
                            )
                            : goWorkDetail(data.orderWork.orderId, data.orderWork.workId);
                      });
                    },
                    function (msg) {
                      if (msg != "no login") {
                        layer.msg(msg);
                      }
                    }
                );*/
            }, 200);
            return false;
        });

        form.on("select(channelId)", function(data) {
            var channelId = data.value;
            // 更新plat
            var channelPlat = $(data.elem).find("option:selected").attr("plat");
            if (channelPlat) {
                $("#plat").val(channelPlat);
            }

            // 清空预发券相关信息，避免数据错误
            clearAllProductDiscountInfo(channelId, null, null);

            // 加载渠道开通的城市，选择渠道时提示
            initCitySelect(getters.getProvinceId(), data.value, true, function() {
                var list = window.EventBus.list;
                list.forEach(function(item, index) {
                    if (window.EventBus.checkRemove(index)) {

            // 设置自动派单时间
            // getAutoDistributeTime(index);

                        renderServCategorySelect(function() {
                            // 更新产品信息
                            initProduct("", "", index);

                            calculateProductAmount(index);

                            // 初始化预约时间
                            initDutyTime(index, function() {
                                // 初始化服务公司信息
                                initCompanyInfo();
                            });

              // 计算派单工程师
              // calculateDistributeMaster(index);
            }, index);
          }
        });
      });
      // 校验当前渠道是否开通选中的城市
      checkChannelIdAndCityId(
          data.value,
          getters.getCityId(),
          "当前渠道未开通：" + getLayuiSelectText("#cityId") + "，请重新选择城市"
      );

      // 获取渠道是否改预付款
      $http.get(GET_CHANNEL_PREPAY_TYPE_URL, {channelId: data.value}).then(function (data) {
            if (data.prepayType == 2) {
              $("#channelPrepayType").removeClass("layui-hide");
              if (data.detailItemList) {
                var detailItem = '';
                $.each(data.detailItemList, function (index, item) {
                  detailItem += '<div class="layui-form-item">' +
                      '<label class="layui-form-label">' + item.text + '</label>' +
                      '<div class="layui-input-inline" style="width: 200px;">' +
                      '<input class="layui-input prepay-amount-item" lay-verify="channel-amount" type="text" autocomplete="off" ></div></div>';
                });
                $("#prepayAmountList").html(detailItem);
              }
            } else {
              $("#channelPrepayType").addClass("layui-hide");
            }
          },
          function (msg) {
            $("#channelPrepayType").addClass("layui-hide");
          });

            //下单渠道是否 选择外部店铺
            checkSelectExternalShop(channelId);

    });

        // 校验服务商的点击事件
        $("#preCompany").on("click", function(e) {
            e.preventDefault();

            var layer = parent.layui.layer;

            var dataList = window.EventBus.list;
            var firstDataIndex = 0;
            dataList.forEach(function(item, index) {
                if (window.EventBus.checkRemove(index)) {
                    firstDataIndex = index;
                    return;
                }
            });

            // 检查产品
            if (!newGetters.getProductId(firstDataIndex)) {
                layer.alert("请选择产品", { offset: "250px" });
                return;
            }

            // 检查城市
            if (!getters.getCityId()) {
                layer.alert("请选择城市", { offset: "250px" });
                return;
            }

            // 检查经纬度
            if (!getters.getLongitude()) {
                layer.alert("请选择经纬度", { offset: "250px" });
                return;
            }

            let plat = getters.getPlatWork();

            let url = OMS_BASE_URL + CHECK_COMPANY_URL;
            if ($(document).attr("title") != "快捷下单") {
                url += "?plat=" + plat;
            }

            layer.open({
                title: "校验服务商",
                type: 2,
                shift: 7,
                area: ["780px", "345px"],
                fix: true,
                zIndex: 99999999999,
                content: url,
                success: function(layero, index) {
                    parent.layer.setTop(layero);
                    parent.window.checkCompanyOptions = {
                        workId: getters.getWorkId(),
                        reworkId: $("#reworkId").val(),
                        type: getters.getOrderType(),
                        recommenderId: $("#recommenderId").val(),
                        channelId: getters.getChannelId(),
                        platWork: getters.getPlatWork(),
                        plat: getters.getPlat(),
                        bizType: getters.getBizType(),
                        cityId: getters.getCityId(),
                        productId: newGetters.getProductId(firstDataIndex),
                        longitude: getters.getLongitude(),
                        latitude: getters.getLatitude(),
                        streetId: getters.getStreetId(),
                        countyId: getters.getCountyId(),
                        dutyTime: newGetters.getDutyTime(firstDataIndex),
                    };
                },
            });
        });

        // 上传预付款图片
        if (document.getElementById("prepayImage")) {
            document.getElementById("prepayImage").addEventListener('paste', function(e) {
                var clipboard = e.clipboardData;
                if (!clipboard || !clipboard.files) {
                    return;
                }
                var imageFile = clipboard.files[0];
                if (!imageFile) {
                    return;
                }
                if (imageFile.type.indexOf("image") > -1) {
                    var form = new FormData();
                    form.append('file', imageFile);
                    $.ajax({
                        url: '/work/modify/uploader/orderPhoto?timestamp=' + new Date().getTime(),
                        type: "POST",
                        data: form,
                        processData: false,
                        contentType: false,
                        error: function() {
                            alert('预付款图片上传失败');
                        },
                        success: function(res) {
                            let data = res.data;
                            $("#channelPrepayCertificateImgSrcValue").val(data);
                            $("#channelPrepayCertificateImgSrcValues").attr("src", data).attr("style", "width: 0;height: 0");
                            reLoadImage('channelPrepayCertificateImgSrc', data);
                        }
                    });
                }
            });
        }

        // 点击放大
        $(document).on('click', '.btn-review', function() {
            let $container = $(this).parent().prev();
            $container.viewer().on('hide', function() {
                $container.viewer('destroy');
            });

            let index = $(this).index();
            $container.viewer('view', index);

        });

        // 点击删除
        $(document).on('click', '.btn-delete', function() {
            let $uploadDiv = $(this).parent().prev();
            $uploadDiv.find(".layui-upload-drag").attr("style", "");
            $uploadDiv.find("i").attr("style", "");
            $uploadDiv.find("p").attr("style", "");
            $uploadDiv.find(":hidden").val("");
            $("#channelPrepayCertificateImgSrcValue").val("");
        });

        // 渠道预付款按钮
        form.on("radio(channelPrepayRadio)", function(data) {
            if (data.value == 2) {
                $("#channelPrepay").removeClass("layui-hide");
            } else {
                $("#channelPrepay").addClass("layui-hide");
                $("#channelPrepayAmount").val("");
                $("#channelPrepayCertificateImgSrcValue").val("");
                $("#channelPrepayCertificateImgSrc").attr("style", "");
                $("#upload-icon").attr("style", "");
                $("#upload-p").attr("style", "");
            }
        });

        // 检查真实手机号
        // checkRealPhoneAndSaveOrder(false);
        if (getters.isCheckRealPhone()) {
            initRealPhone();
        }
        //checkRealPhoneAndSaveOrder(false);

        // 渠道单号输入框输入事件
        $('#outerId').on('input', function() {
            var $this = $(this);
            let data = $this.val().replace(/[^A-Za-z0-9]/g, '');
            if (!data) {
                $this.val(data);
            } else {
                $this.val(data.substr(0, 32));
            }
        });
        $('body').on('paste', '#outerId', function(e) {
            if (this.disabled) {
                return;
            }
            // 粘贴处理
            let $telephone = $(this);
            let pastedData = e.originalEvent.clipboardData.getData('text');
            pastedData = pastedData.replace(/[^A-Za-z0-9]/g, '');
            if (!pastedData) {
                $this.val(pastedData);
            } else {
                $this.val(pastedData.substr(0, 32));
            }
            return false;
        });

        // 报价/话务挽留短信短信初始化
        initCustomerMessageEvent();

        // 初始化提前报价相关事件
        initAdvanceQuoteEvent();
    }

    /**
     * 报价/话务挽留短信短信初始化
     */
    function initCustomerMessageEvent(){
        // 话务挽留短信 - 后台录单 - 话务挽留短信
        $('#sendOrderTransferFailMessageBtn').on('click', function (){
            let telephone = getters.getTelephone();
            if (!telephone) {
                layer.msg('用户电话不能为空！');
                return false;
            }
            let productId = getters.getProductId();
            if (!productId) {
                layer.msg('产品不能为空！');
                return false;
            }

            let hideTel = telephone.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
            layer.open({
                title:'发送挽留短信',
                content: '确定向用户'+hideTel+'发送挽留短信吗？<br>用户可通过短信访问微信小程序对应的商品详情页，查看商品详情',
                btn: ['确认', '取消'],
                yes: function(index, layero) {
                    $http.get(GET_ORDER_TRANSFER_FAIL_URL, {
                        telphone: telephone,
                        productId: productId,
                    }).then(function () {
                        layer.msg('发送成功');
                    });
                },
                cancel: function() {
                },
            });

            return false;
        });

        // 修改订单 - 话务确认报价失败
        $('#sendOrderConfirmQuotedFailMessageBtn').on('click', function (){
            let telephone = getters.getTelephone();
            if (!telephone) {
                layer.msg('用户电话不能为空！');
                return false;
            }
            let productId = getters.getProductId();
            if (!productId) {
                layer.msg('产品不能为空！');
                return false;
            }

            let hideTel = telephone.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
            layer.open({
                title:'发送确认报价短信',
                content: '确定向用户'+hideTel+'用户发送确认报价短信吗？<br>用户可通过商品详情页了解报价或联系客服确认报价',
                btn: ['确认', '取消'],
                yes: function(index, layero) {
                    $http.get(GET_ORDER_CONFIRM_QUOTED_FAIL_URL, {
                        orderId: getters.getOrderId(),
                        telphone: telephone,
                        productId: productId,
                        dutyTime: getters.getDutyTime(),
                    }).then(function () {
                        layer.msg('发送短信成功');
                    });
                },
                cancel: function() {
                },
            });

            return false;
        })
    }

    var verifyRules = {
        // 用户电话验证
        tel: function(value, el) {
            value = $.trim(value);

            if (value === "") {
                return;
            }

            let hideTelephone = $(el).data('val');
            if (hideTelephone && value == hideTelephone) {
                return;
            }

            if (validate.phone(value) || validate.tel(value)) {
                return;
            }

            return "请正确填写您的电话号码";
        },
        mobile: function(value, el) {
            value = $.trim(value);

            if (value === '') {
                return;
            }

            let hideTelephone = $(el).data('val');
            if (hideTelephone && value == hideTelephone) {
                return;
            }

            if (validate.phone(value)) {
                return;
            }

            return '请正确填写您的手机号码';
        },
        // 产品数量
        count: function(value) {
            value = $.trim(value);
            var minValue = 1;
            var maxValue = 10;

            if (getters.getProductShowType() === PRODUCT_SHOW_TYPE_ENUM.FRONT) {
                maxValue = maxProductCount;
            }

            if (!validate.isPosInt(value)) {
                return "请正确填写产品数量";
            } else if (value > maxValue) {
                return "产品数量的最大值为 " + maxValue;
            } else {
                return;
            }
        },
        // 检查原单号
        checkReworkId: function(value) {
            if (getters.getOrderType() === "1") {
                return;
            }

            if (!$.trim(value)) {
                return "必填项不能为空";
            }

            var telephone = getters.getTelephone();
            var productId = getters.getProductId();
            var longitude = getters.getLocation().lng;
            var latitude = getters.getLocation().lat;

            if (!telephone || !productId || !longitude || !latitude) {
                return;
            }

            var flag = false;
            var failMessage;

            checkReworkId(value).then(
                function() {
                    flag = true;
                },
                function(msg) {
                    failMessage = msg || "网络错误，请重试";
                }
            );

            if (!flag) {
                return failMessage;
            }

            return;
        },

        // 验证预约时间
        dutyTime: function(value) {},

        // 验证长度
        maxLengthFactory: function(length) {
            return function(value) {
                if (value.length > length) {
                    return "输入字符超过最大长度，最大长度为：" + length;
                } else {
                    return;
                }
            };
        },
    };

    function dutyStatusCheck(checked, index) {
        if (checked) {
            $("#duty-time-wrapper" + index).hide();
            $("#duty-fail-code").removeClass("layui-hide");
            $("#next-contact-time").removeClass("layui-hide");

            $("#dutyFailCode").attr("lay-verify", "required");
            $("#next-contact-date-input").attr("lay-verify", "required");
            $("#next-contact-time-input").attr("lay-verify", "required");
            $("#duty-time-input").attr("lay-verify", "");

            initDutyTimeInfo("", "", index);
            // 更新服务商信息
            initCompanyInfo();
        } else {
            $("#duty-time-wrapper" + index).show();
            $("#duty-fail-code").addClass("layui-hide");
            $("#next-contact-time").addClass("layui-hide");

      $("#dutyFailCode").attr("lay-verify", "");
      $("#next-contact-date-input").attr("lay-verify", "");
      $("#next-contact-time-input").attr("lay-verify", "");
    }
    // 计算派单工程师
    // calculateDistributeMaster(index);
  }

    function initVerifyRules() {
        form.verify({
            tel: verifyRules.tel,
            mobile: verifyRules.mobile,
            count: verifyRules.count,
            rework: verifyRules.checkReworkId,
            dutyTime: verifyRules.dutyTime,
            maxLenTo500: verifyRules.maxLengthFactory(500),
            maxLenTo300: verifyRules.maxLengthFactory(300),
        });
    }

    /**
     * 清空输入框的值
     */
    function clearInputValue(selector) {
        $(selector).val("");
    }

    /**
     * 清空输入框的值
     */
    function clearSelectValue(selector) {
        var selectedOption = selector + " option:selected";
        $(selectedOption).prop("selected", false);
    }

    /**
     * 显示模糊地址选择框
     */
    function initFuzzyAddress() {
        var $this = $("#address-type-exact");
        $this.addClass("layui-hide");
        $("#exact-address").addClass("layui-hide");
        $("#address-type-fuzzy").removeClass("layui-hide");
        $("#fuzzy-address").removeClass("layui-hide");
        clearAddress();

        $("#customerAddress").attr("lay-verify", "");
        $("#countyId").attr("lay-verify", "required");
        $("#streetId").attr("lay-verify", "required");
    }

    /**
     * 显示精确地址选择框
     */
    function initExactAddress() {
        var $this = $("#address-type-fuzzy");
        $this.addClass("layui-hide");
        $("#fuzzy-address").addClass("layui-hide");
        $("#address-type-exact").removeClass("layui-hide");
        $("#exact-address").removeClass("layui-hide");
        clearAddress();

        $("#customerAddress").attr("lay-verify", "required");
        $("#countyId").attr("lay-verify", "");
        $("#streetId").attr("lay-verify", "");
    }

    /**
     * 初始化精确地址与模糊地址显示
     */
    function initAddressShow(streetId) {
        if (streetId) {
            initFuzzyAddress();
        } else {
            initExactAddress();
        }
    }

    /**
     * 乘法函数，用来得到精确的乘法结果
     * @param {Object} arg1
     * @param {Object} arg2
     */
    function accMul(arg1, arg2) {
        var m = 0;
        m += deal(arg1);
        m += deal(arg2);
        var r1 = Number(arg1.toString().replace(".", ""));
        var r2 = Number(arg2.toString().replace(".", ""));
        return (r1 * r2) / Math.pow(10, m)
    }

    /**
     * 加法函数，用来得到精确的加法结果
     * @param {Object} arg1
     * @param {Object} arg2
     */
    function accAdd(arg1, arg2) {
        var r1 = deal(arg1);
        var r2 = deal(arg2);
        var m = Math.pow(10, Math.max(r1, r2))
        return(arg1 * m + arg2 * m) / m
    }

    /**
     * 求小数点后的数据长度
     */
    function deal(arg) {
        var t = 0;
        try {
            t = arg.toString().split(".")[1].length
        } catch(e) {}
        return t;
    }

    /**
     * 清空地址相关数据
     */
    function clearAddress() {
        var inputArray = ["#customerAddress", "#longitude", "#latitude", "#communityId", "#streetSource"];

        $.each(inputArray, function(index, selector) {
            clearInputValue(selector);
        });

        var selectArray = ["#countyId", "#streetId"];

        $.each(selectArray, function(index, selector) {
            clearSelectValue(selector);
        });

        form.render("select");

        setTimeout(function() {
            $("#suggestPanel ul").html("");
            $("#suggestPanel").hide();
        }, 300);

    initCompanyInfo();
    // calculateAllDistributeMaster();
    clearAllDutyTime();
  }

    /**
     * 重新生成模糊地址数据
     */
    function recreatFuzzyInfo() {
        var $street = $("#streetId option:selected");
        if ($street) {
            var lon = $street.data("longitude");
            var lat = $street.data("latitude");
            var id = $street.val();
            if (!id == "") {
                if (!lon || !lat) {
                    $street.prop("selected", false);
                    layer.msg("所选街道无经纬度数据，请到基础数据中心完善配置");
                    return;
                }
                $("#longitude").val(lon);
                $("#latitude").val(lat);
                $("#customerAddress").val($street.text());
                $('#streetSource').val(3);

                // 如果前面的信息完整就检查服务服务可用性
                // if (checkServiceInfoCompleteness()) {
                //   checkServiceValidation();
                // }
            }
        }
    }

    /**
     * 初始化行政服务商
     */
    function initGridCompany() {

        var dataList = window.EventBus.list;
        var removeList = window.EventBus.removeList;
        var firstDataIndex = 0;
        dataList.forEach(function(item, index) {
            if (window.EventBus.checkRemove(index)) {
                firstDataIndex = index;
                return;
            }
        });

        // 产品大于2不展示
        if (dataList.length - removeList.length > 1) {
            $("#gridCompany").html("");
            return;
        }

        // 平台直派获取行政服务商
        if (isGrid && getters.getStreet() != '' && getters.getLongitude() && getters.getProductId(firstDataIndex)) {
            $("#gridCompany").removeClass("layui-hide");
            $("#company").addClass("layui-hide");
            var reqData = {
                callId: getters.getCallId(),
                clueId: getters.getClueId(),
                plat: getters.getPlatWork(),
                userName: getters.getUserName(),
                gender: getters.getGender(),
                telephone: getters.getTelephone(),
                telephone2: getters.getTelephone2(),
                telephone3: getters.getTelephone3(),
                type: getters.getOrderType(),
                workId: getters.getWorkId(),
                bizType: getters.getBizType(),
                channelId: getters.getChannelId(),
                channelName: getters.getChannelName(),
                provinceId: getters.getProvinceId(),
                provinceName: getters.getProvinceName(),
                cityId: getters.getCityId(),
                cityName: getters.getCityName(),
                countyId: getters.getCountyId(),
                countyName: getters.getInputCountyName(),
                streetSource: getters.getStreetSource(),
                streetId: getters.getStreetId(),
                street: getters.getStreet(),
                address: getters.getAddress(),
                longitude: getters.getLongitude(),
                latitude: getters.getLatitude(),
                dutyTime: newGetters.getDutyTime(firstDataIndex),
                servCategId: newGetters.getServCategId(firstDataIndex),
                productShowType: newGetters.getProductShowType(firstDataIndex),
                productId: newGetters.getProductId(firstDataIndex),
                test: getters.getTest(),
                remark: getters.getRemark(),
                receiveEntranceId: getters.getReceiveEntranceId(),
                requestId: getters.getRequestId()
            };

            $http.$post(GRID_COMPANY_URL, reqData).then(
                function(data) {
                    if (data.message.indexOf('未找到产品信息') != -1) {
                        $("#gridCompany").html("<span>" + data.message + "</span>");
                        isSelectMaster = false
                        $('#confirmbtn').addClass("layui-btn-disabled").attr("disabled", true);
                    } else {
                        $("#gridCompany").html("<span>" + data.message + "</span>");
                        isSelectMaster = true;
                        $('#confirmbtn').removeClass("layui-btn-disabled").attr("disabled", false);
                    }
                },
                function(e) {
                    $("#gridCompany").html("<span style='color: red'>" + e + "</span>");
                    if (e == "无法承接线索") {
                        $("#tips").text("已帮您登记成功，若30min无工程师联系您，建议可以看下其他平台，感谢您的来电，再见！");
                    } else {
                        $("#tips").text("");
                    }
                    isSelectMaster = false;
                    $('#confirmbtn').addClass("layui-btn-disabled").attr("disabled", true);
                }
            );
            $("#preManageCompanyId").val('');
            $("#preManageCompanyName").val('');
        } else {
            $("#gridCompany").addClass("layui-hide");
            $("#gridCompany").html("");
            $("#company").removeClass("layui-hide");
        }
    }

    function goWorkDetail(orderId, workId) {
        if (workId != null && workId != 0) {
            window.location.href =
                objOfURL.workDetail +
                "?" +
                zmnUtils.urlEncode({
                    orderId: orderId,
                    workId: workId,
                });
        } else {
            layer.open({
                content: "下单成功！",
                btn: ["确认"],
                yes: function(index, layero) {
                    location.reload();
                    //parent.layui.admin.events.closeThisTabs();
                },
                cancel: function() {
                    //右上角关闭回调
                    location.reload();
                    //parent.layui.admin.events.closeThisTabs();
                },
            });
        }
    }

    function goWorkModifyDetail(orderId, workId) {
        window.location.href =
            objOfURL.workModifyDetail +
            "?" +
            zmnUtils.urlEncode({
                orderId: orderId,
                workId: workId,
            });
    }

    /**
     * 初始化下次联系时间选择框
     */
    function renderNextTimeDatePicker() {
        var datePickerElem = "#next-contact-date-input";
        var timePickerElem = "#next-contact-time-input";
        var nowDate = $(datePickerElem).data("date");
        var nextHour = $(timePickerElem).data("hour");
        var minDate = $(datePickerElem).data("today-available") ?
            nowDate :
            dayjs(nowDate).add(1, "day").format("YYYY-MM-DD");
        var timePickerInstance;

        laydate.render({
            elem: datePickerElem,
            type: "date",
            format: "yyyy-MM-dd",
            min: minDate,
            done: function(value) {
                var minHour = nowDate === value ? nextHour : 8;
                if (!timePickerInstance) {
                    timePickerInstance = laydate.render({
                        elem: timePickerElem,
                        type: "time",
                        format: "HH:mm:ss",
                        theme: "time-hour",
                        min: minHour + ":00:00",
                        max: "18:00:00",
                        btns: ["clear", "confirm"],
                    });
                } else {
                    timePickerInstance.config.min.hours = minHour;
                }

                // 切换时间选择框的验证状态
                if (value) {
                    $(timePickerElem).attr("lay-verify", "required");
                } else {
                    $(timePickerElem).attr("lay-verify", "");
                }
            },
        });
    }

    /**
     * 初始化订单快递
     */
    function renderNewOrderPost() {
        orderPostTable = table.render({
            elem: "#orderPostTable",
            width: 526,
            data: [],
            cols: [
                [{
                        field: "expressCode",
                        title: "单号",
                        width: "30%",
                        align: "center",
                    },
                    {
                        field: "expressCompany",
                        title: "快递公司",
                        width: "30%",
                        align: "center",
                    },
                    {
                        field: "itemTypeName",
                        title: "类型",
                        width: "20%",
                        align: "center",
                    },
                    { title: "操作", align: "center", toolbar: "#btns" },
                ],
            ],
            done: function() {},
            even: true,
        });

        table.on("tool(orderPostTable)", function(obj) {
            if (obj.event === "del") {
                var postData = table.cache["orderPostTable"];
                postData.splice(obj.tr.data("index"), 1); //根据索引删除当前行
                orderPostTable.reload({
                    data: postData,
                });
            }
        });

        $("#addOrderPost").on("click", function() {
            var expressCode = $("#expressCode").val();
            var expressCompany = $("#expressCompany").val();
            if (zmnUtil.isEmptyNull(expressCode)) {
                layer.msg("请输入快递单号");
                return;
            }
            if (zmnUtil.isEmptyNull(expressCompany)) {
                layer.msg("请选择快递公司");
                return;
            }

            var postDataList = table.cache["orderPostTable"];
            postDataList.push({
                expressCode: expressCode,
                expressCompanyCode: expressCompany,
                expressCompany: $("#expressCompany option:selected").text(),
                itemType: 1,
                itemTypeName: "新机",
            });

            orderPostTable.reload({
                data: postDataList,
            });
        });
    }

    /**
     * 更多
     */
    function initMoreModal() {
        $('[data-toggle="allModal"]').on("click", function() {
            var that = $('[data-toggle="modal"]');
            if (that.hasClass("layui-icon-up")) {
                that.removeClass("layui-icon-up").addClass("layui-icon-down");
            } else {
                that.removeClass("layui-icon-down").addClass("layui-icon-up");
            }

            var targetId = that.data("target");
            if (!targetId) {
                return;
            }
            var $target = $(targetId);
            if ($target.hasClass("layui-hide")) {
                $target.removeClass("layui-hide").addClass("layui-show");
            } else {
                $target.removeClass("layui-show").addClass("layui-hide");
            }
        });
    }

    /**
     * 初始化下拉框
     */
    function initAllSelect() {
        initShopSelect();
    }

    function initShopSelect(){
        if (!options.enableExternalShop) {
            return;
        }
        let customSearch = (selectId, options) => {
            let newOptions = zmnOmsSelect.mergeOptions(selectId, options, {
                propMap: {  //选项参数映射配置
                    name: "showShopName",   //显示值
                    value: "internalShopId",  //选中值
                    internalShopId: "internalShopId",
                    internalShopName: "internalShopName",
                    internalBranchShopName: "internalBranchShopName",
                    externalShopId: "externalShopId",
                    cooperationId: "cooperationId"
                },
                isRadio: true,
                remote: {
                    body: false,
                    enable: true,
                    url: GET_EXTERNAL_SHOP_URL,
                    events: {
                        params: function (searchValue, limitPermit) {
                            return {
                                keyword: searchValue
                            }
                        }
                    }
                }
            })
            return zmnOmsSelect.searchBox(selectId, newOptions);
        }
        let searchBoxDemo = customSearch('externalShopInfo', {
            name: "externalShopInfoSelelct",
            // searchedValue: json.vo.demo4SearchValue,
            // selectedValues: json.vo.demo4Ids, //已选中值（用于回显)
            events: {
                dataMap: function (resultData) {
                    console.log("==========接口返回数据=========");
                    let data = [];
                    if (resultData.status == 200) {
                        data = resultData.data;
                    }
                    return {
                        data: data
                    };
                },
                changed: function (values) {
                    if (!values) {
                        return;
                    }
                    if (values.length < 1) {
                        return;
                    }
                    let externalShopInfo = zmnOmsSelect.getXmSelect('externalShopInfo').getValue()[0];
                    if (!externalShopInfo.cooperationId) {
                        return;
                    }
                    if (!json.channelList) {
                        return;
                    }
                    json.channelList.forEach(function(item, index) {
                        if (externalShopInfo.cooperationId === item.value) {
                            $('#channelId').val(item.value);
                            form.render("select");
                            var select = 'dd[lay-value=' + item.value + ']';
                            $('#channelId').siblings("div.layui-form-select").find('dl').find(select).click();
                            return;
                        }
                    });
                }
            }
        })
    }

    function initClipboardEvent() {
        // 初始化剪切板控制器
        clipboard.init();

        // 初始化剪切板控制器
        let $clipboard = new ClipboardJS('.productCategTip', {
            text: function (trigger) {
                let $productCateg = $('input[name="productCategId"]:checked');
                if ($productCateg.length > 0) {
                    return $productCateg.attr("title");
                } else {
                    return '';
                }
            }
        });

        $clipboard.on('success', function(e) {
            layer.tips('复制成功', e.trigger, {
                time: 500,
                tips: [3, '#5FB878']
            })
        });

        // 初始化剪切板控制器
        let $productClipboard = new ClipboardJS('.quoteProductTip', {
            text: function (trigger) {
                let $quoteProduct = $('input[name="quoteProduct"]:checked');
                if ($quoteProduct.length > 0) {
                    return $quoteProduct.attr("title");
                } else {
                    return '';
                }
            }
        });

        $productClipboard.on('success', function(e) {
            layer.tips('复制成功', e.trigger, {
                time: 500,
                tips: [3, '#5FB878']
            })
        });
    }

    /**
     * 初始化页面
     */
    function initPage(options) {
        // 初始化复制事件
        initClipboardEvent();

        initAllSelect();
        // 初始化区域信息
        initServiceArea(getters.getCityId(), function() {
            var countyId = $("#countyId").attr("value");
            $("#countyId").val(countyId);
            layui.form.render("select");
            updateAreaList(countyId);
        });

        // 初始化下次联系时间选择框
        renderNextTimeDatePicker();

        // 初始化页面事件
        initEvent();

        if (!options || !options.withoutPhoneVerify) {
            // 触发验证会员电话
            $('input[name="telephone"]').trigger("change");
        }

        // 初始化表单验证规则
        initVerifyRules();

        // 复制页面校验渠道城市
        if (options.isCopy) {
            checkChannelIdAndCityId(getters.getChannelId(), getters.getCityId());
        }

        // 更多
        initMoreModal();
        dutyStatusCheck($("#duty-time-checkbox0").is(":checked"), 0);

    if (options.isCopy || getters.getOrderType() == ORDER_TYPE_ENUM.REWORK) {
      // 设置自动派单时间
      // getAutoDistributeTime(0);

            initDutyTime(0, function() {
                initCompanyInfo();
            });

            if (getters.getOrderType() != ORDER_TYPE_ENUM.REWORK) {
            }
        }

        // 加载校验服务商
        if (getters.getCityId()) {
            checkGrid(getters.getCityId());
        }

        uploaderImage("channelPrepayCertificateImgSrc", "channelPrepayCertificateImgSrcValue");

    }
    //初始化新增产品的事件
    function addProductEvenFunc(index) {
        renderServCategorySelect("", index);
        addFormEvent(
            "product" + index,
            "showProduct" + index,
            "servCategory" + index,
            index
        );
        setTimeout(function() {
            var str = "servCategoryA" + index;
            form.render(null, str);
        }, 1000);
    }

    //检查预约时间是否选择
    function checkDutyTime(index) {
        if (!$("#duty-time-checkbox" + index).is(":checked") &&
            !newGetters.getDutyTime(index)
        ) {
            if (getters.getPlatWork() == "1" || getters.getPlatWork() == "3") {
                return true; // 言而有信，一步维修不需要预约时间校验
            }
            return false;
        }
        return true;
    }

    //检查报价信息是否完整
    function checkQuoteInfo(data, index) {
        if (!data.quoteType) {
            return "请选择报价方式";
        }
        if (data.quoteType == "1" && !data.phenId) {
            return "请选择故障现象";
        }
        if (data.quoteType == "2" && !data.itemId) {
            return "请选择服务项";
        }
        if (!data.productCategId) {
            return "请选择产品类别";
        }
        if (!data.quoteProduct) {
            return "请选择产品型号";
        }
        if (!getLayuiSelectValue("#brand0")) {
            return "请选择品牌";
        }
        return undefined;
    }

    /**
     *  校验疫情
     * @param
     */
    function checkEpidemicControl() {
        let obj = {
            longitude: getters.getLongitude(),
            latitude: getters.getLatitude(),
            countyId: getters.getCountyId()
        }

        if (!obj.longitude || !obj.latitude) {
            $("#spanEpidemicControlTip").text('');
            $("#divEpidemicControlTip").text('');
            return;
        }

        $http.get(CHECK_EPIDEMIC_CONTROL_URL, obj).then(
            function (data) {
                if (data === 1) {
                    $("#spanEpidemicControlTip").text('');
                    $("#divEpidemicControlTip")
                        .addClass("epidemicOfOpen")
                        .removeClass("epidemicOfClose")
                        .text("该地址2公里内有：疫情-防控区，请注意疫情防控。");
                } else if (data === 2) {
                    $("#spanEpidemicControlTip").text('很抱歉，由于您提供的地址可能归属管控区，根据相关防疫规定，工程师暂时无法上门服务，给您带来的不便敬请谅解。');
                    $("#divEpidemicControlTip")
                        .addClass("epidemicOfClose")
                        .removeClass("epidemicOfOpen")
                        .text("该地址2公里内有：疫情-管控区，可联系客户是否继续服务。");
                } else if (data === 3) {
                    $("#spanEpidemicControlTip").text('很抱歉，由于您提供的地址可能归属封控区，根据相关防疫规定，工程师暂时无法上门服务，给您带来的不便敬请谅解。');
                    $("#divEpidemicControlTip")
                        .addClass("epidemicOfClose")
                        .removeClass("epidemicOfOpen")
                        .text("该地址2公里内有：疫情-封控区，可联系客户是否继续服务。");
                } else {
                    $("#spanEpidemicControlTip").text('');
                    $("#divEpidemicControlTip").text('');
                }
            },
            function (msg) {
                console.log(msg);
                $("#spanEpidemicControlTip").text('');
                $("#divEpidemicControlTip").text('');
            }
        );
    }

    /**
     *  清空疫情相关参数
     */
    function cleanEpidemicControl() {
        $("#spanEpidemicControlTip").text('');
        $("#divEpidemicControlTip").text('');
    }

  //绑定form事件
  function addFormEvent(prodect, showProdect, servCateg, index) {
    var str = "duty-time-checkbox" + index;
    form.on("checkbox(" + str + ")", function (data) {
      dutyStatusCheck(data.elem.checked, index);
    });
    //报价方式监听
    form.on("radio(quoteType" + index + ")", function (data) {
        if(!newGetters.getBrandId(index)){
            zmnUtils.layui.toastError(
                "请先完善品牌信息"
            );
            console.log(55)
            if($(this).attr("checked")) {
                console.log(123)
                $(this).removeAttr("checked")
                form.render();
            } else {
                console.log(1234)
                $(this).removeAttr("checked")
                form.render();
            }
        }
    });
    // 产品数量输入框的 input 事件、change 事件
    $("#count" + index)
        .on("input", function () {
          var $this = $(this);
          $this.val($this.val().replace(/[^\d]/gi, ""));
        })
        .on("change", function () {
          // 计算价格
          calculateProductAmount(index);
          // 清理预约信息
          clearDutyTime(index);
          // 初始化预约时间
          initDutyTime(index);
          // 计算派单工程师
          // calculateDistributeMaster(index);

            // 提前计价优惠刷新
            reloadAdvanceQuoteDiscount();

        });

      form.on("select(" + prodect + ")", function (data) {
          var eleName = data.elem.name;
          var productId = data.value;
          var list = window.EventBus.list;
          var formData = [];
          list.forEach(function (item, i) {
              if (window.EventBus.checkRemove(i) && i != index) {
                  formData.push({
                      productId: $("select[name='productId" + i + "']").val(),
                      showProductId: $("select[name='showProductId" + i + "']").val(),
                  });
              }
          });
          var platWork = getters.getPlatWork();
          var bizType = getters.getBizType();
          var cityId = getters.getCityId();
          var channelId = getters.getChannelId();
          var brandId = getters.getBrandId();
          formData.push({
              productId: eleName.indexOf("show") != -1 ? "" : productId,
              showProductId: eleName.indexOf("show") != -1 ? productId : "",
          });
          var params = {
              platWork: platWork,
              bizType: bizType,
              cityId: cityId,
              channelId: channelId,
              brandId: brandId,
              productList: formData
          };

          checkProdect(
              params,
              function () {
                  success();
              },
              function () {
                  eleName.indexOf("show") != -1 ?
                      $("select[name='showProductId" + index + "']").val("") :
                      $("select[name='productId" + index + "']").val("");
                  initProduct("", "", index);
              }
          );

          function success() {
              var serviceGategoryId = $(data.elem)
                  .find('option[value="' + productId + '"]')
                  .data("pid");

              if (serviceGategoryId) {
                  $("#servCategoryId" + index).val(serviceGategoryId);
                  form.render("select", "servCategoryA" + index);
              }

              var unit = $(data.elem).find("option:selected").data("unit") || "";

              // 初始化产品数量输入框
              initCountInput(1, index);

              // 初始化产品单位
              initProductUnit(unit, index);
              // 初始化常见故障多选框组
              initCommonFaultsCheckboxGroup(productId, index);

              // 检查报价相关信息
              checkAdvanceQuote();

              // 计算价格
              calculateProductAmount(index);

              // 如果前面的信息完整就检查服务服务可用性
              if (checkServiceInfoCompleteness(index)) {
                  checkServiceValidation(index);
              }

              // 设置自动派单时间
              // getAutoDistributeTime(index);

              // 清理预约信息
              clearDutyTime(index);
              // 初始化预约时间
              initDutyTime(index);

              // initDiscount(index);

              // 检查相同服务分类订单数量
              initOrderSameNumber(index);

              // 初始化行政服务商
              initGridCompany();

              // 计算派单工程师
              // calculateDistributeMaster(index);

              // 检查重复单
              checkDuplicateOrder(index);
              $("#quoteTypeDiv" + index).show();

              EventBus.$emit("productSelect", data);
          }
      });

      form.on("select(" + showProdect + ")", function (data) {
          var productId = data.value;
          var list = window.EventBus.list;
          var formData = [];
          list.forEach(function (item, i) {
              if (
                  window.EventBus.checkRemove(i) &&
                  $("select[name='showProductId" + i + "']").val() != productId
              ) {
                  formData.push({
                      productId: $("select[name='showProductId" + i + "']").val() || null,
                      showProductId: $("select[name='showProductId" + i + "']").val() || null,
                  });
              }
          });
          formData.push({productId: null, showProductId: productId});
          formData;

          var serviceGategoryId = $(data.elem)
              .find('option[value="' + productId + '"]')
              .data("pid");

          if (serviceGategoryId) {
              $("#servCategoryId" + index).val(serviceGategoryId);
              form.render("select", "servCategoryA" + index);
          }

          var unit = $(data.elem).find("option:selected").data("unit") || "";

          // 初始化产品数量输入框
          initCountInput(1, index);

          // 初始化产品单位
          initProductUnit(unit, index);
          // 初始化常见故障多选框组
          initCommonFaultsCheckboxGroup(productId, index);

          // 计算价格
          calculateProductAmount(index);
          // 重新计算预约时间
          // orderSche.reProcessDutyTime();

          // 设置自动派单时间
          // getAutoDistributeTime(index);

          // 清理预约信息
          clearDutyTime(index);
          // 初始化预约时间
          initDutyTime(index, function () {
              // 初始化服务公司信息
              initCompanyInfo();
          });

          // 检查相同服务分类订单数量
          initOrderSameNumber(index);

          // 初始化行政服务商
          initGridCompany();

          // 检查重复单
          checkDuplicateOrder(index);

          // 计算派单工程师
          // calculateDistributeMaster(index);

          // 检查报价相关信息
          checkAdvanceQuote();
          $("#quoteTypeDiv" + index).show();
          
      });

      // 服务分类事件
      form.on("select(" + servCateg + ")", function (data) {
          var servCategId = data.value;

          // 更新下拉框选项状态
          updateOptionsStatus(data.elem, index);

          // 初始化产品下拉框
          initProduct(0, 1, index);

          // 初始化产品数量输入框
          initCountInput(1, index);

          initProductUnit("", index);

          // 初始化品牌下拉框
          initBrandSelect("", index);

          // 初始化常见故障
          initCommonFaultsCheckboxGroup("", index);

          // 如果前面的信息完整就检查服务服务可用性
          if (checkServiceInfoCompleteness(index)) {
              checkServiceValidation(index);
          }

          // 初始化公司信息
          initCompanyInfo();

          // 检查相同服务分类订单数量
          initOrderSameNumber(index);

          // 清理预约信息
          clearDutyTime(index);

          // 处理提前付信息
          checkAdvanceQuote();

          // 计算派单工程师
          // calculateDistributeMaster(index);
      });

      // 服务分类事件
      form.on("select(brand" + index + ")", function (data) {
          let brandId = data.value;

          // 处理提前付逻辑
          setTimeout(function (){
              checkAdvanceQuote()
          }, 200);
      });

        /**
         * 检查相同服务分类订单数量
         * @param index
         */
        function initOrderSameNumber(index) {
            if ($("#callId").val() == undefined) {
                return;
            }

            let servCategId = newGetters.getServCategId(index);
            if (!servCategId) {
                return;
            }

            // 检查相同订单数量
            let params = {
                phone: getters.getTelephone(),
                servCategId: servCategId
            };
            $http.get(GET_ORDER_SAME_NUMBER_URL, params).then(function(data) {
                if (data == 0) {
                    $("#sameNumber" + index).html("");
                } else {
                    $("#sameNumber" + index).attr("data-phone", params.phone).attr("data-servCategId", params.servCategId)
                        .html("<a name='sameNumberClick' style='color: red;cursor: pointer;'>相同服务分类进行中订单数：" + data + "</a>");
                    addSameNumberClick();
                }
            }, function(msg) {
                layer.msg("获取相同服务分类订单失败!");
            });
        }

        // 跳转页面
        function addSameNumberClick() {
            $("a[name='sameNumberClick']").click(function() {
                var $this = $(this);
                let phone = $this.parent().attr("data-phone");
                let servCategId = $this.parent().attr("data-servCategId");
                // /work/list.action?concatPhone=&serviceCategoryId=&workResultStatus=1
                parent.layui.index.openTabsPage(OMS_BASE_URL + ZMN_ORDER_LIST_URL + "?concatPhone=" + phone +
                    "&serviceCategoryId=" + servCategId + "&workResultStatus=1", '工单管理');
                return false;
            });
        }
    }

    // 回车事件处理
    document.onkeydown = function (event) {
        console.log(event, event.code);
        if (event.target.tagName == 'TEXTAREA') {
            return true;
        }
        if (event.code != 'Enter') {
            return true;
        }
        return false;
    }

    exports("mos_order_add_common", {
        init: function(ops) {
            options = ops;

            if (options.isNew === true) {
                // 新增订单，使用渠道开通的城市
                CITY_URL = "/area/channel/city/list.action";
            }

            // 初始化页面
            initPage(ops);
        },
        initCompany: function(cityId) {
            cityId = cityId || getters.getCityId();
            initCompanyInfo();
        },
        getters: getters,
        goDetail: goWorkDetail,
        goModifyDetail: goWorkModifyDetail,
        resetCitySelect: function() {
            renderCitySelect(json.cityList);
        },
        isRework: function() {
            return getters.getOrderType() === "2";
        },
        calculateProductAmount: calculateProductAmount,
        renderNewOrderPost: renderNewOrderPost,
    });
});
